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 | great-expectations__great_expectations | great_expectations/expectations/core/expect_column_parameterized_distribution_ks_test_p_value_to_be_greater_than.py | {
"start": 269,
"end": 817
} | class ____(BatchExpectation):
def __init__(self, *args, **kwargs):
raise NotImplementedError
library_metadata = {
"maturity": "production",
"tags": [
"core expectation",
"column aggregate expectation",
"needs migration to modular expectations api",
],
"contributors": ["@great_expectations"],
"requirements": [],
}
metric_dependencies = tuple()
success_keys = ()
args_keys = ()
| ExpectColumnParameterizedDistributionKsTestPValueToBeGreaterThan |
python | walkccc__LeetCode | solutions/139. Word Break/139-2.py | {
"start": 0,
"end": 396
} | class ____:
def wordBreak(self, s: str, wordDict: list[str]) -> bool:
wordSet = set(wordDict)
@functools.lru_cache(None)
def wordBreak(i: int) -> bool:
"""Returns True if s[i..n) can be segmented."""
if i == len(s):
return True
return any(s[i:j] in wordSet and wordBreak(j)
for j in range(i + 1, len(s) + 1))
return wordBreak(0)
| Solution |
python | yandexdataschool__Practical_RL | week08_pomdp/atari_util.py | {
"start": 95,
"end": 2297
} | class ____(Wrapper):
def __init__(self, env, height=42, width=42, color=False,
crop=lambda img: img, n_frames=4, dim_order='pytorch', reward_scale=1):
"""A gym wrapper that reshapes, crops and scales image into the desired shapes"""
super().__init__(env)
self.img_size = (height, width)
self.crop = crop
self.color = color
self.dim_order = dim_order
self.reward_scale = reward_scale
n_channels = (3 * n_frames) if color else n_frames
obs_shape = {
'pytorch': (n_channels, height, width),
'tensorflow': (height, width, n_channels),
}[dim_order]
self.observation_space = Box(0.0, 1.0, obs_shape)
self.framebuffer = np.zeros(obs_shape, 'float32')
def reset(self, **kwargs):
"""Resets the game, returns initial frames"""
self.framebuffer = np.zeros_like(self.framebuffer)
state, info = self.env.reset(**kwargs)
self.update_buffer(state)
return self.framebuffer, info
def step(self, action):
"""Plays the game for 1 step, returns frame buffer"""
new_img, r, terminated, truncated, info = self.env.step(action)
self.update_buffer(new_img)
return self.framebuffer, r * self.reward_scale, terminated, truncated, info
### image processing ###
def update_buffer(self, img):
img = self.preproc_image(img)
offset = 3 if self.color else 1
if self.dim_order == 'tensorflow':
axis = -1
cropped_framebuffer = self.framebuffer[:, :, :-offset]
else:
axis = 0
cropped_framebuffer = self.framebuffer[:-offset, :, :]
self.framebuffer = np.concatenate([img, cropped_framebuffer], axis=axis)
def preproc_image(self, img):
"""what happens to the observation"""
img = self.crop(img)
img = cv2.resize(img / 255, self.img_size, interpolation=cv2.INTER_LINEAR)
if not self.color:
img = img.mean(-1, keepdims=True)
if self.dim_order != 'tensorflow':
img = img.transpose([2, 0, 1]) # [h, w, c] to [c, h, w]
return img
| PreprocessAtari |
python | HIPS__autograd | autograd/core.py | {
"start": 8361,
"end": 11985
} | class ____:
__slots__ = ["vs", "mut_add"]
def __init__(self, vs, mut_add):
self.vs = vs
self.mut_add = mut_add
VSpace.register(SparseObject, lambda x: x.vs)
SparseBox.register(SparseObject)
sparse_object_types = {SparseObject, SparseBox}
# -------------------- core reverse mode grads --------------------
identity_vjp = lambda argnums, *args: lambda g: g
defvjp(sparse_add, None, identity_vjp, identity_vjp)
defvjp(func(VSpace.add), None, identity_vjp, identity_vjp)
defvjp(func(VSpace.mut_add), None, identity_vjp, identity_vjp)
defvjp(
func(VSpace.inner_prod),
None,
lambda ans, vs, x, y: lambda g: vs.covector(vs.scalar_mul(y, g)),
lambda ans, vs, x, y: lambda g: vs.covector(vs.scalar_mul(x, g)),
)
defvjp(func(VSpace.covector), None, lambda ans, vs, x: lambda g: vs.covector(g))
defvjp(
func(VSpace.scalar_mul),
None,
lambda ans, vs, x, a: lambda g: vs.covector(vs.scalar_mul(vs.covector(g), a)),
lambda ans, vs, x, a: lambda g: vs.inner_prod(g, vs.covector(x)),
)
# -------------------- core forward mode grads --------------------
identity_jvp = lambda g, *args, **kwargs: g
defjvp(sparse_add, None, identity_jvp, identity_jvp)
defjvp(func(VSpace.mut_add), None, identity_jvp, identity_jvp)
defjvp(func(VSpace.add), None, identity_jvp, identity_jvp)
defjvp(func(VSpace.scalar_mul), None, "same", "same")
defjvp(func(VSpace.inner_prod), None, "same", "same")
defjvp(func(VSpace.covector), None, "same")
# -------------------- deprecation warnings -----------------------
import warnings
deprecated_defvjp_message = """
The {} method is deprecated. See the update guide and tutorial:
https://github.com/HIPS/autograd/blob/master/docs/updateguide.md
https://github.com/HIPS/autograd/blob/master/docs/tutorial.md"""
def deprecated_defvjp(primitive_fun):
deprecation_msg = deprecated_defvjp_message.format("defvjp")
vjpfuns = {}
def defvjp_unstaged(vjpmaker, argnum=0):
warnings.warn(deprecation_msg)
def staged_vjpmaker(ans, *args, **kwargs):
def vjp(g):
vs, gvs = vspace(args[argnum]), vspace(g)
return vjpmaker(g, ans, vs, gvs, *args, **kwargs)
return vjp
vjpfuns[argnum] = staged_vjpmaker
argnums, vjpmakers = zip(*[(argnum, vjpfuns[argnum]) for argnum in sorted(vjpfuns.keys())])
defvjp(primitive_fun, *vjpmakers, argnums=argnums)
return defvjp_unstaged
def deprecated_defvjp_is_zero(primitive_fun):
deprecation_msg = deprecated_defvjp_message.format("defvjp_is_zero")
zero_vjps = [set()]
def defvjp_is_zero(argnums=(0,)):
warnings.warn(deprecation_msg)
zero_vjps[0] |= set(argnums)
nones = [None] * len(zero_vjps[0])
defvjp(primitive_fun, *nones, argnums=sorted(zero_vjps[0]))
return defvjp_is_zero
def deprecated_defgrad(primitive_fun):
deprecation_msg = deprecated_defvjp_message.format("defgrad")
gradfuns = {}
def defgrad(gradfun, argnum=0):
warnings.warn(deprecation_msg)
gradfuns[argnum] = gradfun
argnums, vjpmakers = zip(*[(argnum, gradfuns[argnum]) for argnum in sorted(gradfuns.keys())])
defvjp(primitive_fun, *vjpmakers, argnums=argnums)
return defgrad
primitive_ = primitive
def primitive_with_deprecation_warnings(f_raw):
f_wrapped = primitive_(f_raw)
f_wrapped.defvjp = deprecated_defvjp(f_wrapped)
f_wrapped.defvjp_is_zero = deprecated_defvjp_is_zero(f_wrapped)
f_wrapped.defgrad = deprecated_defgrad(f_wrapped)
return f_wrapped
primitive = primitive_with_deprecation_warnings
| SparseObject |
python | facebook__pyre-check | client/commands/infer.py | {
"start": 15583,
"end": 15671
} | class ____(FieldAnnotation):
pass
@dataclasses.dataclass(frozen=True)
| GlobalAnnotation |
python | openai__openai-python | src/openai/types/responses/response_apply_patch_tool_call_output.py | {
"start": 237,
"end": 965
} | class ____(BaseModel):
id: str
"""The unique ID of the apply patch tool call output.
Populated when this item is returned via API.
"""
call_id: str
"""The unique ID of the apply patch tool call generated by the model."""
status: Literal["completed", "failed"]
"""The status of the apply patch tool call output. One of `completed` or `failed`."""
type: Literal["apply_patch_call_output"]
"""The type of the item. Always `apply_patch_call_output`."""
created_by: Optional[str] = None
"""The ID of the entity that created this tool call output."""
output: Optional[str] = None
"""Optional textual output returned by the apply patch tool."""
| ResponseApplyPatchToolCallOutput |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/dataclass9.py | {
"start": 204,
"end": 528
} | class ____(Protocol):
# Checking for this attribute seems to currently be
# the most reliable way to ascertain that something is a dataclass
__dataclass_fields__: ClassVar[dict[str, Any]]
def dataclass_only(
x: IsDataclass,
): ... # do something that only makes sense with a dataclass
@dataclass
| IsDataclass |
python | apache__airflow | airflow-core/src/airflow/metrics/otel_logger.py | {
"start": 11357,
"end": 15682
} | class ____:
"""Stores Otel Instruments."""
def __init__(self, meter):
self.meter = meter
self.map = {}
def clear(self) -> None:
self.map.clear()
def _create_counter(self, name):
"""Create a new counter or up_down_counter for the provided name."""
otel_safe_name = _get_otel_safe_name(name)
if _is_up_down_counter(name):
counter = self.meter.create_up_down_counter(name=otel_safe_name)
else:
counter = self.meter.create_counter(name=otel_safe_name)
log.debug("Created %s as type: %s", otel_safe_name, _type_as_str(counter))
return counter
def get_counter(self, name: str, attributes: Attributes = None):
"""
Return the counter; creates a new one if it did not exist.
:param name: The name of the counter to fetch or create.
:param attributes: Counter attributes, used to generate a unique key to store the counter.
"""
key = _generate_key_name(name, attributes)
if key not in self.map:
self.map[key] = self._create_counter(name)
return self.map[key]
def del_counter(self, name: str, attributes: Attributes = None) -> None:
"""
Delete a counter.
:param name: The name of the counter to delete.
:param attributes: Counter attributes which were used to generate a unique key to store the counter.
"""
key = _generate_key_name(name, attributes)
if key in self.map.keys():
del self.map[key]
def set_gauge_value(self, name: str, value: int | float, delta: bool, tags: Attributes):
"""
Override the last reading for a Gauge with a new value.
:param name: The name of the gauge to record.
:param value: The new reading to record.
:param delta: If True, value is added to the previous reading, else it overrides.
:param tags: Gauge attributes which were used to generate a unique key to store the counter.
:returns: None
"""
key: str = _generate_key_name(name, tags)
if key not in self.map:
self.map[key] = InternalGauge(meter=self.meter, name=name, tags=tags)
self.map[key].set_value(value, delta)
def get_otel_logger(cls) -> SafeOtelLogger:
host = conf.get("metrics", "otel_host") # ex: "breeze-otel-collector"
port = conf.getint("metrics", "otel_port") # ex: 4318
prefix = conf.get("metrics", "otel_prefix") # ex: "airflow"
ssl_active = conf.getboolean("metrics", "otel_ssl_active")
# PeriodicExportingMetricReader will default to an interval of 60000 millis.
conf_interval = conf.getfloat("metrics", "otel_interval_milliseconds", fallback=None) # ex: 30000
debug = conf.getboolean("metrics", "otel_debugging_on")
service_name = conf.get("metrics", "otel_service")
resource = Resource.create(attributes={HOST_NAME: get_hostname(), SERVICE_NAME: service_name})
protocol = "https" if ssl_active else "http"
# Allow transparent support for standard OpenTelemetry SDK environment variables.
# https://opentelemetry.io/docs/specs/otel/protocol/exporter/#configuration-options
endpoint = os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT", f"{protocol}://{host}:{port}")
metrics_endpoint = os.environ.get("OTEL_EXPORTER_OTLP_METRICS_ENDPOINT", f"{endpoint}/v1/metrics")
# https://opentelemetry.io/docs/specs/otel/configuration/sdk-environment-variables/#periodic-exporting-metricreader
if interval := os.environ.get("OTEL_METRIC_EXPORT_INTERVAL", conf_interval):
interval = float(interval)
log.info("[Metric Exporter] Connecting to OpenTelemetry Collector at %s", endpoint)
readers = [
PeriodicExportingMetricReader(
OTLPMetricExporter(endpoint=metrics_endpoint),
export_interval_millis=interval, # type: ignore[arg-type]
)
]
if debug:
export_to_console = PeriodicExportingMetricReader(ConsoleMetricExporter())
readers.append(export_to_console)
metrics.set_meter_provider(
MeterProvider(
resource=resource,
metric_readers=readers,
shutdown_on_exit=False,
),
)
return SafeOtelLogger(metrics.get_meter_provider(), prefix, get_validator())
| MetricsMap |
python | joke2k__faker | tests/providers/test_person.py | {
"start": 58874,
"end": 61553
} | class ____(unittest.TestCase):
def setUp(self):
self.fake = Faker("sw")
Faker.seed(0)
def test_last_name(self):
"""
Test the generation of Swahili last names.
"""
# There's no gender-specific last name in Swahili.
self.assertTrue(hasattr(SwProvider, "last_names_male"))
self.assertTrue(hasattr(SwProvider, "last_names_female"))
# All last names apply to all genders.
self.assertTrue(hasattr(SwProvider, "last_names"))
# General last name.
name = self.fake.last_name()
self.assertIsInstance(name, str)
self.assertIn(name, SwProvider.last_names)
# Females last name.
name = self.fake.last_name_female()
self.assertIsInstance(name, str)
self.assertIn(name, SwProvider.last_names)
# Male last name.
name = self.fake.last_name_male()
self.assertIsInstance(name, str)
self.assertIn(name, SwProvider.last_names)
def test_first_name(self):
"""
Test the generation of Swahili first names.
"""
# General first name.
name = self.fake.first_name()
self.assertIsInstance(name, str)
self.assertIn(name, SwProvider.first_names)
# Female first name.
name = self.fake.first_name_female()
self.assertIsInstance(name, str)
self.assertIn(name, SwProvider.first_names)
self.assertIn(name, SwProvider.first_names_female)
# Male first name.
name = self.fake.first_name_male()
self.assertIsInstance(name, str)
self.assertIn(name, SwProvider.first_names)
self.assertIn(name, SwProvider.first_names_male)
def test_full_name(self):
"""
Test the generation of full Swahili names.
"""
# Full name.
name = self.fake.name()
self.assertIsInstance(name, str)
full_name_parts = name.split()
if len(full_name_parts) == 2:
first_name = full_name_parts[0]
last_name = full_name_parts[1]
self.assertIn(first_name, SwProvider.first_names)
self.assertIn(last_name, SwProvider.last_names)
elif len(full_name_parts) == 3:
prefix = full_name_parts[0]
first_name = full_name_parts[1]
last_name = full_name_parts[2]
self.assertIn(prefix, SwProvider.prefixes_female + SwProvider.prefixes_male)
self.assertIn(first_name, SwProvider.first_names)
self.assertIn(last_name, SwProvider.last_names)
else:
raise AssertionError("Invalid number of name parts. Expected 2 or 3.")
| TestSw |
python | gevent__gevent | src/gevent/queue.py | {
"start": 17804,
"end": 22127
} | class ____(SimpleQueue):
"""
A subclass of :class:`SimpleQueue` that additionally has
:meth:`task_done` and :meth:`join` methods.
.. versionchanged:: 25.4.1
Renamed from ``JoinablQueue`` to simply ``Queue`` to better
match the capability of the standard library :class:`queue.Queue`.
"""
__slots__ = (
'_cond',
'unfinished_tasks',
)
def __init__(self, maxsize=None, items=(), unfinished_tasks=None):
"""
.. versionchanged:: 1.1a1
If *unfinished_tasks* is not given, then all the given *items*
(if any) will be considered unfinished.
"""
SimpleQueue.__init__(self, maxsize, items, _warn_depth=3)
from gevent.event import Event
self._cond = Event()
self._cond.set()
if unfinished_tasks:
self.unfinished_tasks = unfinished_tasks
elif items:
self.unfinished_tasks = len(items)
else:
self.unfinished_tasks = 0
if self.unfinished_tasks:
self._cond.clear()
def copy(self):
return type(self)(self.maxsize, self.queue, self.unfinished_tasks)
def _format(self):
result = SimpleQueue._format(self)
if self.unfinished_tasks:
result += ' tasks=%s _cond=%s' % (self.unfinished_tasks, self._cond)
return result
def _put(self, item):
SimpleQueue._put(self, item)
self._did_put_task()
def _did_put_task(self):
self.unfinished_tasks += 1
self._cond.clear()
def task_done(self):
'''Indicate that a formerly enqueued task is complete. Used by queue consumer threads.
For each :meth:`get <Queue.get>` used to fetch a task, a subsequent call to
:meth:`task_done` tells the queue that the processing on the task is complete.
If a :meth:`join` is currently blocking, it will resume when all items have been processed
(meaning that a :meth:`task_done` call was received for every item that had been
:meth:`put <Queue.put>` into the queue).
Raises a :exc:`ValueError` if called more times than there were items placed in the queue.
'''
if self.unfinished_tasks <= 0:
raise ValueError('task_done() called too many times')
self.unfinished_tasks -= 1
if self.unfinished_tasks == 0:
self._cond.set()
def join(self, timeout=None):
'''
Block until all items in the queue have been gotten and processed.
The count of unfinished tasks goes up whenever an item is added to the queue.
The count goes down whenever a consumer thread calls :meth:`task_done` to indicate
that the item was retrieved and all work on it is complete. When the count of
unfinished tasks drops to zero, :meth:`join` unblocks.
:param float timeout: If not ``None``, then wait no more than this time in seconds
for all tasks to finish.
:return: ``True`` if all tasks have finished; if ``timeout`` was given and expired before
all tasks finished, ``False``.
.. versionchanged:: 1.1a1
Add the *timeout* parameter.
'''
return self._cond.wait(timeout=timeout)
def shutdown(self, immediate=False):
"""
"Shut-down the queue, making queue gets and puts raise
`ShutDown`.
By default, gets will only raise once the queue is empty. Set
*immediate* to True to make gets raise immediately instead.
All blocked callers of `put` and `get` will be unblocked.
In joinable queues, if *immediate*, a task is marked as done
for each item remaining in the queue, which may unblock
callers of `join`.
"""
self.is_shutdown = True
if immediate:
self._drain_for_immediate_shutdown()
getters = list(self.getters)
putters = list(self.putters)
self.getters.clear()
self.putters.clear()
for waiter in getters + putters:
self.hub.loop.run_callback(waiter.throw, ShutDown)
def _drain_for_immediate_shutdown(self):
while self.qsize():
self.get()
self.task_done()
#: .. versionchanged:: 25.4.1
#: Now a BWC alias
JoinableQueue = Queue
| Queue |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/engine/row.py | {
"start": 9755,
"end": 9902
} | class ____(ROMappingView, typing.ItemsView["_KeyType", Any]):
__slots__ = ("_items",) # mapping slot is provided by ItemsView
| ROMappingItemsView |
python | huggingface__transformers | src/transformers/models/pvt_v2/modeling_pvt_v2.py | {
"start": 10336,
"end": 12191
} | class ____(nn.Module):
def __init__(self, config: PvtV2Config, layer_idx: int, drop_path: float = 0.0):
super().__init__()
hidden_size: int = config.hidden_sizes[layer_idx]
num_attention_heads: int = config.num_attention_heads[layer_idx]
spatial_reduction_ratio: int = config.sr_ratios[layer_idx]
mlp_ratio: float = config.mlp_ratios[layer_idx]
self.layer_norm_1 = nn.LayerNorm(hidden_size, eps=config.layer_norm_eps)
self.attention = PvtV2SelfAttention(
config=config,
hidden_size=hidden_size,
num_attention_heads=num_attention_heads,
spatial_reduction_ratio=spatial_reduction_ratio,
)
self.drop_path = PvtV2DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
self.layer_norm_2 = nn.LayerNorm(hidden_size, eps=config.layer_norm_eps)
mlp_hidden_size = int(hidden_size * mlp_ratio)
self.mlp = PvtV2ConvFeedForwardNetwork(config=config, in_features=hidden_size, hidden_features=mlp_hidden_size)
def forward(self, hidden_states: torch.Tensor, height: int, width: int, output_attentions: bool = False):
self_attention_outputs = self.attention(
hidden_states=self.layer_norm_1(hidden_states),
height=height,
width=width,
output_attentions=output_attentions,
)
attention_output = self_attention_outputs[0]
outputs = self_attention_outputs[1:]
attention_output = self.drop_path(attention_output)
hidden_states = attention_output + hidden_states
mlp_output = self.mlp(self.layer_norm_2(hidden_states), height, width)
mlp_output = self.drop_path(mlp_output)
layer_output = hidden_states + mlp_output
outputs = (layer_output,) + outputs
return outputs
| PvtV2BlockLayer |
python | great-expectations__great_expectations | great_expectations/exceptions/exceptions.py | {
"start": 2214,
"end": 2404
} | class ____(CheckpointError):
def __init__(self, name: str) -> None:
super().__init__(f"Checkpoint '{name}' not found. Please check the name and try again.")
| CheckpointNotFoundError |
python | keras-team__keras | guides/making_new_layers_and_models_via_subclassing.py | {
"start": 1244,
"end": 2348
} | class ____(keras.layers.Layer):
def __init__(self, units=32, input_dim=32):
super().__init__()
self.w = self.add_weight(
shape=(input_dim, units),
initializer="random_normal",
trainable=True,
)
self.b = self.add_weight(
shape=(units,), initializer="zeros", trainable=True
)
def call(self, inputs):
return ops.matmul(inputs, self.w) + self.b
"""
You would use a layer by calling it on some tensor input(s), much like a Python
function.
"""
x = ops.ones((2, 2))
linear_layer = Linear(4, 2)
y = linear_layer(x)
print(y)
"""
Note that the weights `w` and `b` are automatically tracked by the layer upon
being set as layer attributes:
"""
assert linear_layer.weights == [linear_layer.w, linear_layer.b]
"""
## Layers can have non-trainable weights
Besides trainable weights, you can add non-trainable weights to a layer as
well. Such weights are meant not to be taken into account during
backpropagation, when you are training the layer.
Here's how to add and use a non-trainable weight:
"""
| Linear |
python | google__pytype | pytype/load_pytd.py | {
"start": 11236,
"end": 13086
} | class ____:
"""Resolves late types, loading modules as needed."""
def __init__(self, loader: "Loader"):
self._loader = loader
self._resolved_late_types = {} # performance cache
def _load_late_type_module(self, late_type: pytd.LateType):
"""Load the module of a late type from the qualified name."""
parts = late_type.name.split(".")
for i in range(len(parts) - 1):
module_parts = module_utils.strip_init_suffix(parts[: -(i + 1)])
if ast := self._loader.import_name(".".join(module_parts)):
return ast, ".".join(parts[-(i + 1) :])
return None, late_type.name
def _load_late_type(self, late_type: pytd.LateType):
"""Resolve a late type, possibly by loading a module."""
if late_type.name not in self._resolved_late_types:
if ast := self._loader.import_name(late_type.name):
t = pytd.Module(name=late_type.name, module_name=late_type.name)
else:
ast, attr_name = self._load_late_type_module(late_type)
if ast is None:
msg = "During dependency resolution, couldn't resolve late type %r"
log.error(msg, late_type.name)
t = pytd.AnythingType()
else:
try:
cls = pytd.LookupItemRecursive(ast, attr_name)
except KeyError:
if "__getattr__" not in ast:
log.warning("Couldn't resolve %s", late_type.name)
t = pytd.AnythingType()
else:
t = pytd.ToType(cls, allow_functions=True)
if isinstance(t, pytd.LateType):
t = self._load_late_type(t)
self._resolved_late_types[late_type.name] = t
return self._resolved_late_types[late_type.name]
def load_late_type(self, late_type: pytd.LateType) -> pytd.Type:
"""Convert a pytd.LateType to a pytd type."""
return self._load_late_type(late_type)
| _LateTypeLoader |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 502333,
"end": 502950
} | class ____(sgqlc.types.relay.Connection):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("edges", "nodes", "page_info", "total_count")
edges = sgqlc.types.Field(
sgqlc.types.list_of("ProjectNextEdge"), graphql_name="edges"
)
nodes = sgqlc.types.Field(sgqlc.types.list_of("ProjectNext"), graphql_name="nodes")
page_info = sgqlc.types.Field(
sgqlc.types.non_null(PageInfo), graphql_name="pageInfo"
)
total_count = sgqlc.types.Field(
sgqlc.types.non_null(Int), graphql_name="totalCount"
)
| ProjectNextConnection |
python | networkx__networkx | networkx/utils/decorators.py | {
"start": 10949,
"end": 44713
} | class ____:
"""A decorator to apply a map to arguments before calling the function
This class provides a decorator that maps (transforms) arguments of the function
before the function is called. Thus for example, we have similar code
in many functions to determine whether an argument is the number of nodes
to be created, or a list of nodes to be handled. The decorator provides
the code to accept either -- transforming the indicated argument into a
list of nodes before the actual function is called.
This decorator class allows us to process single or multiple arguments.
The arguments to be processed can be specified by string, naming the argument,
or by index, specifying the item in the args list.
Parameters
----------
func : callable
The function to apply to arguments
*args : iterable of (int, str or tuple)
A list of parameters, specified either as strings (their names), ints
(numerical indices) or tuples, which may contain ints, strings, and
(recursively) tuples. Each indicates which parameters the decorator
should map. Tuples indicate that the map function takes (and returns)
multiple parameters in the same order and nested structure as indicated
here.
try_finally : bool (default: False)
When True, wrap the function call in a try-finally block with code
for the finally block created by `func`. This is used when the map
function constructs an object (like a file handle) that requires
post-processing (like closing).
Note: try_finally decorators cannot be used to decorate generator
functions.
Examples
--------
Most of these examples use `@argmap(...)` to apply the decorator to
the function defined on the next line.
In the NetworkX codebase however, `argmap` is used within a function to
construct a decorator. That is, the decorator defines a mapping function
and then uses `argmap` to build and return a decorated function.
A simple example is a decorator that specifies which currency to report money.
The decorator (named `convert_to`) would be used like::
@convert_to("US_Dollars", "income")
def show_me_the_money(name, income):
print(f"{name} : {income}")
And the code to create the decorator might be::
def convert_to(currency, which_arg):
def _convert(amount):
if amount.currency != currency:
amount = amount.to_currency(currency)
return amount
return argmap(_convert, which_arg)
Despite this common idiom for argmap, most of the following examples
use the `@argmap(...)` idiom to save space.
Here's an example use of argmap to sum the elements of two of the functions
arguments. The decorated function::
@argmap(sum, "xlist", "zlist")
def foo(xlist, y, zlist):
return xlist - y + zlist
is syntactic sugar for::
def foo(xlist, y, zlist):
x = sum(xlist)
z = sum(zlist)
return x - y + z
and is equivalent to (using argument indexes)::
@argmap(sum, "xlist", 2)
def foo(xlist, y, zlist):
return xlist - y + zlist
or::
@argmap(sum, "zlist", 0)
def foo(xlist, y, zlist):
return xlist - y + zlist
Transforming functions can be applied to multiple arguments, such as::
def swap(x, y):
return y, x
# the 2-tuple tells argmap that the map `swap` has 2 inputs/outputs.
@argmap(swap, ("a", "b")):
def foo(a, b, c):
return a / b * c
is equivalent to::
def foo(a, b, c):
a, b = swap(a, b)
return a / b * c
More generally, the applied arguments can be nested tuples of strings or ints.
The syntax `@argmap(some_func, ("a", ("b", "c")))` would expect `some_func` to
accept 2 inputs with the second expected to be a 2-tuple. It should then return
2 outputs with the second a 2-tuple. The returns values would replace input "a"
"b" and "c" respectively. Similarly for `@argmap(some_func, (0, ("b", 2)))`.
Also, note that an index larger than the number of named parameters is allowed
for variadic functions. For example::
def double(a):
return 2 * a
@argmap(double, 3)
def overflow(a, *args):
return a, args
print(overflow(1, 2, 3, 4, 5, 6)) # output is 1, (2, 3, 8, 5, 6)
**Try Finally**
Additionally, this `argmap` class can be used to create a decorator that
initiates a try...finally block. The decorator must be written to return
both the transformed argument and a closing function.
This feature was included to enable the `open_file` decorator which might
need to close the file or not depending on whether it had to open that file.
This feature uses the keyword-only `try_finally` argument to `@argmap`.
For example this map opens a file and then makes sure it is closed::
def open_file(fn):
f = open(fn)
return f, lambda: f.close()
The decorator applies that to the function `foo`::
@argmap(open_file, "file", try_finally=True)
def foo(file):
print(file.read())
is syntactic sugar for::
def foo(file):
file, close_file = open_file(file)
try:
print(file.read())
finally:
close_file()
and is equivalent to (using indexes)::
@argmap(open_file, 0, try_finally=True)
def foo(file):
print(file.read())
Here's an example of the try_finally feature used to create a decorator::
def my_closing_decorator(which_arg):
def _opener(path):
if path is None:
path = open(path)
fclose = path.close
else:
# assume `path` handles the closing
fclose = lambda: None
return path, fclose
return argmap(_opener, which_arg, try_finally=True)
which can then be used as::
@my_closing_decorator("file")
def fancy_reader(file=None):
# this code doesn't need to worry about closing the file
print(file.read())
Decorators with try_finally = True cannot be used with generator functions,
because the `finally` block is evaluated before the generator is exhausted::
@argmap(open_file, "file", try_finally=True)
def file_to_lines(file):
for line in file.readlines():
yield line
is equivalent to::
def file_to_lines_wrapped(file):
for line in file.readlines():
yield line
def file_to_lines_wrapper(file):
try:
file = open_file(file)
return file_to_lines_wrapped(file)
finally:
file.close()
which behaves similarly to::
def file_to_lines_whoops(file):
file = open_file(file)
file.close()
for line in file.readlines():
yield line
because the `finally` block of `file_to_lines_wrapper` is executed before
the caller has a chance to exhaust the iterator.
Notes
-----
An object of this class is callable and intended to be used when
defining a decorator. Generally, a decorator takes a function as input
and constructs a function as output. Specifically, an `argmap` object
returns the input function decorated/wrapped so that specified arguments
are mapped (transformed) to new values before the decorated function is called.
As an overview, the argmap object returns a new function with all the
dunder values of the original function (like `__doc__`, `__name__`, etc).
Code for this decorated function is built based on the original function's
signature. It starts by mapping the input arguments to potentially new
values. Then it calls the decorated function with these new values in place
of the indicated arguments that have been mapped. The return value of the
original function is then returned. This new function is the function that
is actually called by the user.
Three additional features are provided.
1) The code is lazily compiled. That is, the new function is returned
as an object without the code compiled, but with all information
needed so it can be compiled upon it's first invocation. This saves
time on import at the cost of additional time on the first call of
the function. Subsequent calls are then just as fast as normal.
2) If the "try_finally" keyword-only argument is True, a try block
follows each mapped argument, matched on the other side of the wrapped
call, by a finally block closing that mapping. We expect func to return
a 2-tuple: the mapped value and a function to be called in the finally
clause. This feature was included so the `open_file` decorator could
provide a file handle to the decorated function and close the file handle
after the function call. It even keeps track of whether to close the file
handle or not based on whether it had to open the file or the input was
already open. So, the decorated function does not need to include any
code to open or close files.
3) The maps applied can process multiple arguments. For example,
you could swap two arguments using a mapping, or transform
them to their sum and their difference. This was included to allow
a decorator in the `quality.py` module that checks that an input
`partition` is a valid partition of the nodes of the input graph `G`.
In this example, the map has inputs `(G, partition)`. After checking
for a valid partition, the map either raises an exception or leaves
the inputs unchanged. Thus many functions that make this check can
use the decorator rather than copy the checking code into each function.
More complicated nested argument structures are described below.
The remaining notes describe the code structure and methods for this
class in broad terms to aid in understanding how to use it.
Instantiating an `argmap` object simply stores the mapping function and
the input identifiers of which arguments to map. The resulting decorator
is ready to use this map to decorate any function. Calling that object
(`argmap.__call__`, but usually done via `@my_decorator`) a lazily
compiled thin wrapper of the decorated function is constructed,
wrapped with the necessary function dunder attributes like `__doc__`
and `__name__`. That thinly wrapped function is returned as the
decorated function. When that decorated function is called, the thin
wrapper of code calls `argmap._lazy_compile` which compiles the decorated
function (using `argmap.compile`) and replaces the code of the thin
wrapper with the newly compiled code. This saves the compilation step
every import of networkx, at the cost of compiling upon the first call
to the decorated function.
When the decorated function is compiled, the code is recursively assembled
using the `argmap.assemble` method. The recursive nature is needed in
case of nested decorators. The result of the assembly is a number of
useful objects.
sig : the function signature of the original decorated function as
constructed by :func:`argmap.signature`. This is constructed
using `inspect.signature` but enhanced with attribute
strings `sig_def` and `sig_call`, and other information
specific to mapping arguments of this function.
This information is used to construct a string of code defining
the new decorated function.
wrapped_name : a unique internally used name constructed by argmap
for the decorated function.
functions : a dict of the functions used inside the code of this
decorated function, to be used as `globals` in `exec`.
This dict is recursively updated to allow for nested decorating.
mapblock : code (as a list of strings) to map the incoming argument
values to their mapped values.
finallys : code (as a list of strings) to provide the possibly nested
set of finally clauses if needed.
mutable_args : a bool indicating whether the `sig.args` tuple should be
converted to a list so mutation can occur.
After this recursive assembly process, the `argmap.compile` method
constructs code (as strings) to convert the tuple `sig.args` to a list
if needed. It joins the defining code with appropriate indents and
compiles the result. Finally, this code is evaluated and the original
wrapper's implementation is replaced with the compiled version (see
`argmap._lazy_compile` for more details).
Other `argmap` methods include `_name` and `_count` which allow internally
generated names to be unique within a python session.
The methods `_flatten` and `_indent` process the nested lists of strings
into properly indented python code ready to be compiled.
More complicated nested tuples of arguments also allowed though
usually not used. For the simple 2 argument case, the argmap
input ("a", "b") implies the mapping function will take 2 arguments
and return a 2-tuple of mapped values. A more complicated example
with argmap input `("a", ("b", "c"))` requires the mapping function
take 2 inputs, with the second being a 2-tuple. It then must output
the 3 mapped values in the same nested structure `(newa, (newb, newc))`.
This level of generality is not often needed, but was convenient
to implement when handling the multiple arguments.
See Also
--------
not_implemented_for
open_file
nodes_or_number
py_random_state
networkx.algorithms.community.quality.require_partition
"""
def __init__(self, func, *args, try_finally=False):
self._func = func
self._args = args
self._finally = try_finally
@staticmethod
def _lazy_compile(func):
"""Compile the source of a wrapped function
Assemble and compile the decorated function, and intrusively replace its
code with the compiled version's. The thinly wrapped function becomes
the decorated function.
Parameters
----------
func : callable
A function returned by argmap.__call__ which is in the process
of being called for the first time.
Returns
-------
func : callable
The same function, with a new __code__ object.
Notes
-----
It was observed in NetworkX issue #4732 [1] that the import time of
NetworkX was significantly bloated by the use of decorators: over half
of the import time was being spent decorating functions. This was
somewhat improved by a change made to the `decorator` library, at the
cost of a relatively heavy-weight call to `inspect.Signature.bind`
for each call to the decorated function.
The workaround we arrived at is to do minimal work at the time of
decoration. When the decorated function is called for the first time,
we compile a function with the same function signature as the wrapped
function. The resulting decorated function is faster than one made by
the `decorator` library, so that the overhead of the first call is
'paid off' after a small number of calls.
References
----------
[1] https://github.com/networkx/networkx/issues/4732
"""
real_func = func.__argmap__.compile(func.__wrapped__)
func.__code__ = real_func.__code__
func.__globals__.update(real_func.__globals__)
func.__dict__.update(real_func.__dict__)
return func
def __call__(self, f):
"""Construct a lazily decorated wrapper of f.
The decorated function will be compiled when it is called for the first time,
and it will replace its own __code__ object so subsequent calls are fast.
Parameters
----------
f : callable
A function to be decorated.
Returns
-------
func : callable
The decorated function.
See Also
--------
argmap._lazy_compile
"""
def func(*args, __wrapper=None, **kwargs):
return argmap._lazy_compile(__wrapper)(*args, **kwargs)
# standard function-wrapping stuff
func.__name__ = f.__name__
func.__doc__ = f.__doc__
func.__defaults__ = f.__defaults__
func.__kwdefaults__.update(f.__kwdefaults__ or {})
func.__module__ = f.__module__
func.__qualname__ = f.__qualname__
func.__dict__.update(f.__dict__)
func.__wrapped__ = f
# now that we've wrapped f, we may have picked up some __dict__ or
# __kwdefaults__ items that were set by a previous argmap. Thus, we set
# these values after those update() calls.
# If we attempt to access func from within itself, that happens through
# a closure -- which trips an error when we replace func.__code__. The
# standard workaround for functions which can't see themselves is to use
# a Y-combinator, as we do here.
func.__kwdefaults__["_argmap__wrapper"] = func
# this self-reference is here because functools.wraps preserves
# everything in __dict__, and we don't want to mistake a non-argmap
# wrapper for an argmap wrapper
func.__self__ = func
# this is used to variously call self.assemble and self.compile
func.__argmap__ = self
if hasattr(f, "__argmap__"):
func.__is_generator = f.__is_generator
else:
func.__is_generator = inspect.isgeneratorfunction(f)
if self._finally and func.__is_generator:
raise nx.NetworkXError("argmap cannot decorate generators with try_finally")
return func
__count = 0
@classmethod
def _count(cls):
"""Maintain a globally-unique identifier for function names and "file" names
Note that this counter is a class method reporting a class variable
so the count is unique within a Python session. It could differ from
session to session for a specific decorator depending on the order
that the decorators are created. But that doesn't disrupt `argmap`.
This is used in two places: to construct unique variable names
in the `_name` method and to construct unique fictitious filenames
in the `_compile` method.
Returns
-------
count : int
An integer unique to this Python session (simply counts from zero)
"""
cls.__count += 1
return cls.__count
_bad_chars = re.compile("[^a-zA-Z0-9_]")
@classmethod
def _name(cls, f):
"""Mangle the name of a function to be unique but somewhat human-readable
The names are unique within a Python session and set using `_count`.
Parameters
----------
f : str or object
Returns
-------
name : str
The mangled version of `f.__name__` (if `f.__name__` exists) or `f`
"""
f = f.__name__ if hasattr(f, "__name__") else f
fname = re.sub(cls._bad_chars, "_", f)
return f"argmap_{fname}_{cls._count()}"
def compile(self, f):
"""Compile the decorated function.
Called once for a given decorated function -- collects the code from all
argmap decorators in the stack, and compiles the decorated function.
Much of the work done here uses the `assemble` method to allow recursive
treatment of multiple argmap decorators on a single decorated function.
That flattens the argmap decorators, collects the source code to construct
a single decorated function, then compiles/executes/returns that function.
The source code for the decorated function is stored as an attribute
`_code` on the function object itself.
Note that Python's `compile` function requires a filename, but this
code is constructed without a file, so a fictitious filename is used
to describe where the function comes from. The name is something like:
"argmap compilation 4".
Parameters
----------
f : callable
The function to be decorated
Returns
-------
func : callable
The decorated file
"""
sig, wrapped_name, functions, mapblock, finallys, mutable_args = self.assemble(
f
)
call = f"{sig.call_sig.format(wrapped_name)}#"
mut_args = f"{sig.args} = list({sig.args})" if mutable_args else ""
body = argmap._indent(sig.def_sig, mut_args, mapblock, call, finallys)
code = "\n".join(body)
locl = {}
globl = dict(functions.values())
filename = f"{self.__class__} compilation {self._count()}"
compiled = compile(code, filename, "exec")
exec(compiled, globl, locl)
func = locl[sig.name]
func._code = code
return func
def assemble(self, f):
"""Collects components of the source for the decorated function wrapping f.
If `f` has multiple argmap decorators, we recursively assemble the stack of
decorators into a single flattened function.
This method is part of the `compile` method's process yet separated
from that method to allow recursive processing. The outputs are
strings, dictionaries and lists that collect needed info to
flatten any nested argmap-decoration.
Parameters
----------
f : callable
The function to be decorated. If f is argmapped, we assemble it.
Returns
-------
sig : argmap.Signature
The function signature as an `argmap.Signature` object.
wrapped_name : str
The mangled name used to represent the wrapped function in the code
being assembled.
functions : dict
A dictionary mapping id(g) -> (mangled_name(g), g) for functions g
referred to in the code being assembled. These need to be present
in the ``globals`` scope of ``exec`` when defining the decorated
function.
mapblock : list of lists and/or strings
Code that implements mapping of parameters including any try blocks
if needed. This code will precede the decorated function call.
finallys : list of lists and/or strings
Code that implements the finally blocks to post-process the
arguments (usually close any files if needed) after the
decorated function is called.
mutable_args : bool
True if the decorator needs to modify positional arguments
via their indices. The compile method then turns the argument
tuple into a list so that the arguments can be modified.
"""
# first, we check if f is already argmapped -- if that's the case,
# build up the function recursively.
# > mapblock is generally a list of function calls of the sort
# arg = func(arg)
# in addition to some try-blocks if needed.
# > finallys is a recursive list of finally blocks of the sort
# finally:
# close_func_1()
# finally:
# close_func_2()
# > functions is a dict of functions used in the scope of our decorated
# function. It will be used to construct globals used in compilation.
# We make functions[id(f)] = name_of_f, f to ensure that a given
# function is stored and named exactly once even if called by
# nested decorators.
if hasattr(f, "__argmap__") and f.__self__ is f:
(
sig,
wrapped_name,
functions,
mapblock,
finallys,
mutable_args,
) = f.__argmap__.assemble(f.__wrapped__)
functions = dict(functions) # shallow-copy just in case
else:
sig = self.signature(f)
wrapped_name = self._name(f)
mapblock, finallys = [], []
functions = {id(f): (wrapped_name, f)}
mutable_args = False
if id(self._func) in functions:
fname, _ = functions[id(self._func)]
else:
fname, _ = functions[id(self._func)] = self._name(self._func), self._func
# this is a bit complicated -- we can call functions with a variety of
# nested arguments, so long as their input and output are tuples with
# the same nested structure. e.g. ("a", "b") maps arguments a and b.
# A more complicated nesting like (0, (3, 4)) maps arguments 0, 3, 4
# expecting the mapping to output new values in the same nested shape.
# The ability to argmap multiple arguments was necessary for
# the decorator `nx.algorithms.community.quality.require_partition`, and
# while we're not taking full advantage of the ability to handle
# multiply-nested tuples, it was convenient to implement this in
# generality because the recursive call to `get_name` is necessary in
# any case.
applied = set()
def get_name(arg, first=True):
nonlocal mutable_args
if isinstance(arg, tuple):
name = ", ".join(get_name(x, False) for x in arg)
return name if first else f"({name})"
if arg in applied:
raise nx.NetworkXError(f"argument {arg} is specified multiple times")
applied.add(arg)
if arg in sig.names:
return sig.names[arg]
elif isinstance(arg, str):
if sig.kwargs is None:
raise nx.NetworkXError(
f"name {arg} is not a named parameter and this function doesn't have kwargs"
)
return f"{sig.kwargs}[{arg!r}]"
else:
if sig.args is None:
raise nx.NetworkXError(
f"index {arg} not a parameter index and this function doesn't have args"
)
mutable_args = True
return f"{sig.args}[{arg - sig.n_positional}]"
if self._finally:
# here's where we handle try_finally decorators. Such a decorator
# returns a mapped argument and a function to be called in a
# finally block. This feature was required by the open_file
# decorator. The below generates the code
#
# name, final = func(name) #<--append to mapblock
# try: #<--append to mapblock
# ... more argmapping and try blocks
# return WRAPPED_FUNCTION(...)
# ... more finally blocks
# finally: #<--prepend to finallys
# final() #<--prepend to finallys
#
for a in self._args:
name = get_name(a)
final = self._name(name)
mapblock.append(f"{name}, {final} = {fname}({name})")
mapblock.append("try:")
finallys = ["finally:", f"{final}()#", "#", finallys]
else:
mapblock.extend(
f"{name} = {fname}({name})" for name in map(get_name, self._args)
)
return sig, wrapped_name, functions, mapblock, finallys, mutable_args
@classmethod
def signature(cls, f):
r"""Construct a Signature object describing `f`
Compute a Signature so that we can write a function wrapping f with
the same signature and call-type.
Parameters
----------
f : callable
A function to be decorated
Returns
-------
sig : argmap.Signature
The Signature of f
Notes
-----
The Signature is a namedtuple with names:
name : a unique version of the name of the decorated function
signature : the inspect.signature of the decorated function
def_sig : a string used as code to define the new function
call_sig : a string used as code to call the decorated function
names : a dict keyed by argument name and index to the argument's name
n_positional : the number of positional arguments in the signature
args : the name of the VAR_POSITIONAL argument if any, i.e. \*theseargs
kwargs : the name of the VAR_KEYWORDS argument if any, i.e. \*\*kwargs
These named attributes of the signature are used in `assemble` and `compile`
to construct a string of source code for the decorated function.
"""
sig = inspect.signature(f, follow_wrapped=False)
def_sig = []
call_sig = []
names = {}
kind = None
args = None
kwargs = None
npos = 0
for i, param in enumerate(sig.parameters.values()):
# parameters can be position-only, keyword-or-position, keyword-only
# in any combination, but only in the order as above. we do edge
# detection to add the appropriate punctuation
prev = kind
kind = param.kind
if prev == param.POSITIONAL_ONLY != kind:
# the last token was position-only, but this one isn't
def_sig.append("/")
if (
param.VAR_POSITIONAL
!= prev
!= param.KEYWORD_ONLY
== kind
!= param.VAR_POSITIONAL
):
# param is the first keyword-only arg and isn't starred
def_sig.append("*")
# star arguments as appropriate
if kind == param.VAR_POSITIONAL:
name = "*" + param.name
args = param.name
count = 0
elif kind == param.VAR_KEYWORD:
name = "**" + param.name
kwargs = param.name
count = 0
else:
names[i] = names[param.name] = param.name
name = param.name
count = 1
# assign to keyword-only args in the function call
if kind == param.KEYWORD_ONLY:
call_sig.append(f"{name} = {name}")
else:
npos += count
call_sig.append(name)
def_sig.append(name)
fname = cls._name(f)
def_sig = f"def {fname}({', '.join(def_sig)}):"
call_sig = f"return {{}}({', '.join(call_sig)})"
return cls.Signature(fname, sig, def_sig, call_sig, names, npos, args, kwargs)
Signature = collections.namedtuple(
"Signature",
[
"name",
"signature",
"def_sig",
"call_sig",
"names",
"n_positional",
"args",
"kwargs",
],
)
@staticmethod
def _flatten(nestlist, visited):
"""flattens a recursive list of lists that doesn't have cyclic references
Parameters
----------
nestlist : iterable
A recursive list of objects to be flattened into a single iterable
visited : set
A set of object ids which have been walked -- initialize with an
empty set
Yields
------
Non-list objects contained in nestlist
"""
for thing in nestlist:
if isinstance(thing, list):
if id(thing) in visited:
raise ValueError("A cycle was found in nestlist. Be a tree.")
else:
visited.add(id(thing))
yield from argmap._flatten(thing, visited)
else:
yield thing
_tabs = " " * 64
@staticmethod
def _indent(*lines):
"""Indent list of code lines to make executable Python code
Indents a tree-recursive list of strings, following the rule that one
space is added to the tab after a line that ends in a colon, and one is
removed after a line that ends in an hashmark.
Parameters
----------
*lines : lists and/or strings
A recursive list of strings to be assembled into properly indented
code.
Returns
-------
code : str
Examples
--------
argmap._indent(*["try:", "try:", "pass#", "finally:", "pass#", "#",
"finally:", "pass#"])
renders to
'''try:
try:
pass#
finally:
pass#
#
finally:
pass#'''
"""
depth = 0
for line in argmap._flatten(lines, set()):
yield f"{argmap._tabs[:depth]}{line}"
depth += (line[-1:] == ":") - (line[-1:] == "#")
| argmap |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 138389,
"end": 138537
} | class ____(BaseModel, extra="forbid"):
max_length: Optional[int] = Field(default=None, description="Max length of sparse vector")
| StrictModeSparse |
python | getsentry__sentry | src/sentry/sentry_apps/api/bases/sentryapps.py | {
"start": 15942,
"end": 16738
} | class ____(IntegrationPlatformEndpoint):
permission_classes: tuple[type[BasePermission], ...] = (SentryAppInstallationPermission,)
def convert_args(self, request: Request, uuid, *args, **kwargs):
installations = app_service.get_many(filter=dict(uuids=[uuid]))
installation = installations[0] if installations else None
if installation is None:
raise SentryAppError(
message="Could not find given sentry app installation",
status_code=404,
)
self.check_object_permissions(request, installation)
sentry_sdk.get_isolation_scope().set_tag("sentry_app_installation", installation.uuid)
kwargs["installation"] = installation
return (args, kwargs)
| SentryAppInstallationBaseEndpoint |
python | keras-team__keras | keras/src/layers/convolutional/conv_transpose_test.py | {
"start": 17095,
"end": 27901
} | class ____(testing.TestCase):
@parameterized.parameters(
{
"filters": 5,
"kernel_size": 2,
"strides": 2,
"padding": "valid",
"output_padding": None,
"data_format": "channels_last",
"dilation_rate": 1,
},
{
"filters": 6,
"kernel_size": 2,
"strides": 3,
"padding": "same",
"output_padding": 2,
"data_format": "channels_last",
"dilation_rate": (1,),
},
{
"filters": 6,
"kernel_size": (2,),
"strides": (2,),
"padding": "valid",
"output_padding": None,
"data_format": "channels_last",
"dilation_rate": 1,
},
)
def test_conv1d_transpose(
self,
filters,
kernel_size,
strides,
padding,
output_padding,
data_format,
dilation_rate,
):
layer = layers.Conv1DTranspose(
filters=filters,
kernel_size=kernel_size,
strides=strides,
padding=padding,
output_padding=output_padding,
data_format=data_format,
dilation_rate=dilation_rate,
)
inputs = np.random.normal(size=[2, 8, 4])
layer.build(input_shape=inputs.shape)
kernel_shape = layer.kernel.shape
kernel_weights = np.random.normal(size=kernel_shape)
bias_weights = np.random.normal(size=(filters,))
layer.kernel.assign(kernel_weights)
layer.bias.assign(bias_weights)
outputs = layer(inputs)
expected = np_conv1d_transpose(
inputs,
kernel_weights,
bias_weights,
strides,
padding,
output_padding,
data_format,
dilation_rate,
)
self.assertAllClose(outputs, expected, atol=1e-5)
@parameterized.parameters(
{
"filters": 5,
"kernel_size": 2,
"strides": 2,
"padding": "valid",
"output_padding": None,
"data_format": "channels_last",
"dilation_rate": 1,
},
{
"filters": 6,
"kernel_size": 7,
"strides": 16,
"padding": "same",
"output_padding": 2,
"data_format": "channels_last",
"dilation_rate": (1, 1),
},
{
"filters": 6,
"kernel_size": (2, 3),
"strides": (2, 1),
"padding": "valid",
"output_padding": None,
"data_format": "channels_last",
"dilation_rate": (1, 1),
},
{
"filters": 2,
"kernel_size": (7, 7),
"strides": (16, 16),
"padding": "valid",
"output_padding": None,
"data_format": "channels_last",
"dilation_rate": (1, 1),
},
)
def test_conv2d_transpose(
self,
filters,
kernel_size,
strides,
padding,
output_padding,
data_format,
dilation_rate,
):
layer = layers.Conv2DTranspose(
filters=filters,
kernel_size=kernel_size,
strides=strides,
padding=padding,
output_padding=output_padding,
data_format=data_format,
dilation_rate=dilation_rate,
)
inputs = np.random.normal(size=[2, 14, 14, 4])
layer.build(input_shape=inputs.shape)
kernel_shape = layer.kernel.shape
kernel_weights = np.random.normal(size=kernel_shape)
bias_weights = np.random.normal(size=(filters,))
layer.kernel.assign(kernel_weights)
layer.bias.assign(bias_weights)
outputs = layer(inputs)
expected = np_conv2d_transpose(
inputs,
kernel_weights,
bias_weights,
strides,
padding,
output_padding,
data_format,
dilation_rate,
)
self.assertAllClose(outputs, expected, atol=1e-5)
@parameterized.parameters(
{
"filters": 5,
"kernel_size": 2,
"strides": 2,
"padding": "valid",
"output_padding": None,
"data_format": "channels_last",
"dilation_rate": 1,
},
{
"filters": 6,
"kernel_size": 2,
"strides": 3,
"padding": "same",
"output_padding": 2,
"data_format": "channels_last",
"dilation_rate": (1, 1, 1),
},
{
"filters": 6,
"kernel_size": (2, 2, 3),
"strides": (2, 1, 2),
"padding": "valid",
"output_padding": None,
"data_format": "channels_last",
"dilation_rate": (1, 1, 1),
},
)
def test_conv3d_transpose(
self,
filters,
kernel_size,
strides,
padding,
output_padding,
data_format,
dilation_rate,
):
layer = layers.Conv3DTranspose(
filters=filters,
kernel_size=kernel_size,
strides=strides,
padding=padding,
output_padding=output_padding,
data_format=data_format,
dilation_rate=dilation_rate,
)
inputs = np.random.normal(size=[2, 8, 8, 8, 4])
layer.build(input_shape=inputs.shape)
kernel_shape = layer.kernel.shape
kernel_weights = np.random.normal(size=kernel_shape)
bias_weights = np.random.normal(size=(filters,))
layer.kernel.assign(kernel_weights)
layer.bias.assign(bias_weights)
outputs = layer(inputs)
expected = np_conv3d_transpose(
inputs,
kernel_weights,
bias_weights,
strides,
padding,
output_padding,
data_format,
dilation_rate,
)
self.assertAllClose(outputs, expected, atol=1e-5)
@parameterized.product(
kernel_size=list(range(1, 5)),
strides=list(range(1, 5)),
padding=["same", "valid"],
output_padding=[None] + list(range(1, 5)),
)
def test_conv1d_transpose_consistency(
self, kernel_size, strides, padding, output_padding
):
"""Test conv transpose, on an 1D array of size 3, against several
convolution parameters. In particular, tests if Torch inconsistencies
are raised.
"""
# output_padding cannot be greater than strides
if isinstance(output_padding, int) and output_padding >= strides:
pytest.skip(
"`output_padding` greater than `strides` is not supported"
)
if backend.config.image_data_format() == "channels_last":
input_shape = (1, 3, 1)
else:
input_shape = (1, 1, 3)
input = np.ones(shape=input_shape)
kernel_weights = np.arange(1, kernel_size + 1).reshape(
(kernel_size, 1, 1)
)
# Expected result
expected_res = np_conv1d_transpose(
x=input,
kernel_weights=kernel_weights,
bias_weights=np.zeros(shape=(1,)),
strides=strides,
padding=padding,
output_padding=output_padding,
data_format=backend.config.image_data_format(),
dilation_rate=1,
)
# keras layer
kc_layer = layers.Conv1DTranspose(
filters=1,
kernel_size=kernel_size,
strides=strides,
padding=padding,
output_padding=output_padding,
dilation_rate=1,
)
kc_layer.build(input_shape=input_shape)
kc_layer.kernel.assign(kernel_weights)
# Special cases for Torch
if backend.backend() == "torch":
# Args that cause output_padding >= strides
# are clamped with a warning.
if (kernel_size, strides, padding, output_padding) in [
(2, 1, "same", None),
(4, 1, "same", None),
]:
clamped_output_padding = strides - 1 # usually 0 when stride=1
expected_res = np_conv1d_transpose(
x=input,
kernel_weights=kernel_weights,
bias_weights=np.zeros(shape=(1,)),
strides=strides,
padding=padding,
output_padding=clamped_output_padding,
data_format=backend.config.image_data_format(),
dilation_rate=1,
)
with pytest.warns(UserWarning):
kc_res = kc_layer(input)
self.assertAllClose(expected_res, kc_res, atol=1e-5)
return
# torch_padding > 0 and torch_output_padding > 0 case
# Torch output differs from TF.
(
torch_padding,
torch_output_padding,
) = _convert_conv_transpose_padding_args_from_keras_to_torch(
kernel_size=kernel_size,
stride=strides,
dilation_rate=1,
padding=padding,
output_padding=output_padding,
)
if torch_padding > 0 and torch_output_padding > 0:
with pytest.raises(AssertionError):
kc_res = kc_layer(input)
self.assertAllClose(expected_res, kc_res, atol=1e-5)
return
# Compare results
kc_res = kc_layer(input)
self.assertAllClose(expected_res, kc_res, atol=1e-5)
@parameterized.product(
kernel_size=list(range(1, 5)),
strides=list(range(1, 5)),
padding=["same", "valid"],
output_padding=[None] + list(range(1, 5)),
)
def test_shape_inference_static_unknown_shape(
self, kernel_size, strides, padding, output_padding
):
if backend.config.image_data_format() == "channels_last":
input_shape = (None, None, 3)
output_tensor_shape = (None, None, None, 2)
else:
input_shape = (3, None, None)
output_tensor_shape = (None, 2, None, None)
x = layers.Input(shape=input_shape)
x = layers.Conv2DTranspose(
filters=2,
kernel_size=kernel_size,
strides=strides,
padding=padding,
output_padding=output_padding,
dilation_rate=1,
)(x)
self.assertEqual(x.shape, output_tensor_shape)
| ConvTransposeCorrectnessTest |
python | scrapy__scrapy | scrapy/utils/datatypes.py | {
"start": 5126,
"end": 6206
} | class ____(weakref.WeakKeyDictionary):
"""
A weakref.WeakKeyDictionary implementation that uses LocalCache as its
underlying data structure, making it ordered and capable of being size-limited.
Useful for memoization, while avoiding keeping received
arguments in memory only because of the cached references.
Note: like LocalCache and unlike weakref.WeakKeyDictionary,
it cannot be instantiated with an initial dictionary.
"""
def __init__(self, limit: int | None = None):
super().__init__()
self.data: LocalCache = LocalCache(limit=limit)
def __setitem__(self, key: _KT, value: _VT) -> None:
# if raised, key is not weak-referenceable, skip caching
with contextlib.suppress(TypeError):
super().__setitem__(key, value)
def __getitem__(self, key: _KT) -> _VT | None: # type: ignore[override]
try:
return super().__getitem__(key)
except (TypeError, KeyError):
return None # key is either not weak-referenceable or not cached
| LocalWeakReferencedCache |
python | tensorflow__tensorflow | tensorflow/python/saved_model/save_test.py | {
"start": 41392,
"end": 53271
} | class ____(test.TestCase):
def testOpNameSpace(self):
# TODO(kathywu): Add test that saves out SavedModel with a custom op when
# the ">" character is allowed in op names.
graph_def = graph_pb2.GraphDef()
text_format.Parse("node { name: 'A' op: 'Test>CustomOp' }", graph_def)
with self.assertRaisesRegex(
ValueError, "Attempted to save ops from non-whitelisted namespaces"):
save._verify_ops(graph_def, [])
save._verify_ops(graph_def, ["Test"])
# Test with multiple carrots in op name.
text_format.Parse("node { name: 'A' op: 'Test>>A>CustomOp' }", graph_def)
with self.assertRaisesRegex(
ValueError, "Attempted to save ops from non-whitelisted namespaces"):
save._verify_ops(graph_def, [])
save._verify_ops(graph_def, ["Test"])
def test_save_custom_op_with_no_whitelist_specified(self):
# Test that we are able to save a model that contains a custom op with a
# custom namespace when the user has not explicitly specified a namespace
# whitelist (i.e. that we default to allowing all custom ops when saving
# and no whitelist is specified, rather than throwing an exception).
graph_def = graph_pb2.GraphDef()
text_format.Parse("node { name: 'A' op: 'Test>CustomOp' }", graph_def)
save._verify_ops(graph_def, namespace_whitelist=None)
# If the user passes an empty list for the namespace whitelist rather than
# nothing, we should then throw an exception if a custom op is used.
with self.assertRaisesRegex(
ValueError, "Attempted to save ops from non-whitelisted namespaces"
):
save._verify_ops(graph_def, [])
def test_strip_debug_nodes(self):
# Test that we are able to strip debug nodes from a meta_graph correctly.
test_node_defs = [
node_def_pb2.NodeDef(
name="AssertNode",
op="Assert",
input=[
"NonControlInput:output:0",
"^ControlInput:output:0",
],
attr={
"regular_node_attr": attr_value_pb2.AttrValue(i=1),
"_non_regular_node_attr": attr_value_pb2.AttrValue(i=2),
}
),
node_def_pb2.NodeDef(
name="ConstNode",
op="Const",
),
node_def_pb2.NodeDef(
name="CheckNumericsNode",
op="CheckNumerics",
input=[
"NonControlInput:output:0",
"NonControlInputTwo:output:0",
"^ControlInput:output:0",
],
attr={
"T": attr_value_pb2.AttrValue(i=4),
"NotT": attr_value_pb2.AttrValue(i=5),
}
),
node_def_pb2.NodeDef(
name="CheckNumericsNodeTwo",
op="CheckNumerics",
input=[
"NonControlInput:output:0",
"NonControlInputTwo:output:0",
"^ControlInput:output:0",
],
attr={
"OnlyNotT": attr_value_pb2.AttrValue(i=6),
},
),
node_def_pb2.NodeDef(
name="PrintNode",
op="Print",
input=[
"NonControlInput:output:0",
],
),
node_def_pb2.NodeDef(
name="PrintV2Node",
op="PrintV2",
input=[
"NonControlInput:output:0",
],
),
]
expected_node_defs = [
node_def_pb2.NodeDef(
name="AssertNode",
op="NoOp",
input=[
"^NonControlInput",
"^ControlInput:output:0",
],
attr={
"_non_regular_node_attr": attr_value_pb2.AttrValue(i=2),
}
),
node_def_pb2.NodeDef(
name="ConstNode",
op="Const",
),
node_def_pb2.NodeDef(
name="CheckNumericsNode",
op="Identity",
input=[
"NonControlInput:output:0",
"^NonControlInputTwo",
"^ControlInput:output:0",
],
attr={
"T": attr_value_pb2.AttrValue(i=4),
}
),
node_def_pb2.NodeDef(
name="CheckNumericsNodeTwo",
op="Identity",
input=[
"NonControlInput:output:0",
"^NonControlInputTwo",
"^ControlInput:output:0",
],
),
node_def_pb2.NodeDef(
name="PrintNode",
op="Identity",
input=[
"NonControlInput:output:0",
],
),
node_def_pb2.NodeDef(
name="PrintV2Node",
op="NoOp",
input=[
"^NonControlInput",
],
),
]
meta_graph_def = meta_graph_pb2.MetaGraphDef(
graph_def=graph_pb2.GraphDef(
node=test_node_defs,
library=function_pb2.FunctionDefLibrary(
function=[function_pb2.FunctionDef(node_def=test_node_defs)]
),
),
)
expected = meta_graph_pb2.MetaGraphDef(
graph_def=graph_pb2.GraphDef(
node=expected_node_defs,
library=function_pb2.FunctionDefLibrary(
function=[function_pb2.FunctionDef(node_def=expected_node_defs)]
),
),
)
save._strip_debug_nodes(meta_graph_def)
self.assertEqual(expected, meta_graph_def)
def test_save_debug_info_enabled(self):
root = autotrackable.AutoTrackable()
root.f = def_function.function(
lambda x: math_ops.mul(2.0, x, name="DEBUG_INFO_OP"),
input_signature=[tensor_spec.TensorSpec(None, dtypes.float32)],
)
save_dir = os.path.join(self.get_temp_dir(), "saved_model")
save.save(
root,
save_dir,
root.f,
options=save_options.SaveOptions(save_debug_info=True),
)
debug_info_file_name = os.path.join(
save_dir, "debug", "saved_model_debug_info.pb"
)
self.assertTrue(os.path.exists(debug_info_file_name))
debug_info = graph_debug_info_pb2.GraphDebugInfo()
with open(debug_info_file_name, "rb") as f:
debug_info.ParseFromString(f.read())
# Verify that there is a trace for DEBUG_INFO_OP just to ensure that
# function debug info tracing is nominally functioning.
found_op = False
for key in debug_info.name_to_trace_id.keys():
if key.startswith("DEBUG_INFO_OP@"):
found_op = True
break
self.assertTrue(
found_op, "Did not find DEBUG_INFO_OP in trace: %s" % debug_info
)
def test_save_debug_info_disabled(self):
root = autotrackable.AutoTrackable()
root.f = def_function.function(
lambda x: math_ops.mul(2., x, name="DEBUG_INFO_OP"),
input_signature=[tensor_spec.TensorSpec(None, dtypes.float32)])
save_dir = os.path.join(self.get_temp_dir(), "saved_model")
save.save(
root,
save_dir,
root.f,
options=save_options.SaveOptions(save_debug_info=False))
debug_info_file_name = os.path.join(save_dir, "debug",
"saved_model_debug_info.pb")
self.assertFalse(os.path.exists(debug_info_file_name))
def test_function_aliases(self):
root = autotrackable.AutoTrackable()
root.f = def_function.function(
lambda x: 2. * x,
input_signature=[tensor_spec.TensorSpec(None, dtypes.float32)])
save_dir = os.path.join(self.get_temp_dir(), "saved_model")
options = save_options.SaveOptions(
function_aliases={
"my_func": root.f,
}
)
save.save(root, save_dir, root.f, options=options)
function_cache = root.f._variable_creation_config.function_cache.values()
function_aliases = loader_impl.parse_saved_model(
save_dir).meta_graphs[0].meta_info_def.function_aliases
self.assertLen(function_cache, 1)
self.assertEqual(function_cache[0].name.decode("utf-8"),
list(function_aliases.keys())[0])
def test_concrete_function_aliases(self):
root = autotrackable.AutoTrackable()
f = def_function.function(
lambda x: 2.0 * x,
input_signature=[tensor_spec.TensorSpec(None, dtypes.float32)],
).get_concrete_function()
save_dir = os.path.join(self.get_temp_dir(), "saved_model")
options = save_options.SaveOptions(
function_aliases={
"my_func": f,
}
)
save.save(root, save_dir, f, options=options)
function_aliases = loader_impl.parse_saved_model(
save_dir).meta_graphs[0].meta_info_def.function_aliases
self.assertEqual(f.name.decode("utf-8"),
list(function_aliases.keys())[0])
def test_concrete_function_list_aliases(self):
root = autotrackable.AutoTrackable()
f = def_function.function(lambda z: {"out": z * z})
f1 = f.get_concrete_function(tensor_spec.TensorSpec(None, dtypes.float32))
f2 = f.get_concrete_function(tensor_spec.TensorSpec(None, dtypes.int32))
save_dir = os.path.join(self.get_temp_dir(), "saved_model")
options = save_options.SaveOptions(
function_aliases={
"my_func": [f1, f2],
}
)
save.save(root, save_dir, f1, options=options)
function_aliases = (
loader_impl.parse_saved_model(save_dir)
.meta_graphs[0]
.meta_info_def.function_aliases
)
self.assertSameElements(
[f1.name.decode("utf-8"), f2.name.decode("utf-8")],
list(function_aliases.keys()),
)
def test_function_aliases_incorrect_type(self):
root = autotrackable.AutoTrackable()
save_dir = os.path.join(self.get_temp_dir(), "saved_model")
f = lambda x: 2.0 * x
root.f = def_function.function(
f, input_signature=[tensor_spec.TensorSpec(None, dtypes.float32)]
)
options = save_options.SaveOptions(
function_aliases={
"my_func": f,
}
)
with self.assertRaisesRegex(TypeError, "Unsupported type"):
save.save(root, save_dir, root.f, options=options)
def test_accepts_io_device(self):
options = save_options.SaveOptions()
self.assertIsNone(options.experimental_io_device)
options = save_options.SaveOptions(experimental_io_device="/job:localhost")
self.assertEqual("/job:localhost", options.experimental_io_device)
def test_accepts_variable_policy(self):
options = save_options.SaveOptions()
self.assertEqual(save_options.VariablePolicy.NONE,
options.experimental_variable_policy)
# VariablePolicy instances.
options = save_options.SaveOptions(experimental_variable_policy=save_options
.VariablePolicy.SAVE_VARIABLE_DEVICES)
self.assertEqual(save_options.VariablePolicy.SAVE_VARIABLE_DEVICES,
options.experimental_variable_policy)
options = save_options.SaveOptions(
experimental_variable_policy=save_options.VariablePolicy
.EXPAND_DISTRIBUTED_VARIABLES)
self.assertEqual(save_options.VariablePolicy.EXPAND_DISTRIBUTED_VARIABLES,
options.experimental_variable_policy)
# String conversions.
options = save_options.SaveOptions(
experimental_variable_policy="save_variable_devices")
self.assertEqual(save_options.VariablePolicy.SAVE_VARIABLE_DEVICES,
options.experimental_variable_policy)
options = save_options.SaveOptions(
experimental_variable_policy="expand_distributed_variables")
self.assertEqual(save_options.VariablePolicy.EXPAND_DISTRIBUTED_VARIABLES,
options.experimental_variable_policy)
with self.assertRaisesRegex(ValueError, "invalid VariablePolicy value"):
options = save_options.SaveOptions(
experimental_variable_policy="not_a_valid_value")
| SavingOptionsTest |
python | bokeh__bokeh | src/bokeh/models/dom.py | {
"start": 8300,
"end": 8542
} | class ____(ValueRef):
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
hex = Bool(default=True)
swatch = Bool(default=True)
| ColorRef |
python | django-crispy-forms__django-crispy-forms | crispy_forms/layout.py | {
"start": 8712,
"end": 11057
} | class ____(BaseInput):
"""
Used to create a Submit button descriptor for the {% crispy %} template tag.
Attributes
----------
template: str
The default template which this Layout Object will be rendered
with.
field_classes: str
CSS classes to be applied to the ``<input>``.
input_type: str
The ``type`` attribute of the ``<input>``.
Parameters
----------
name : str
The name attribute of the button.
value : str
The value attribute of the button.
css_id : str, optional
A custom DOM id for the layout object. If not provided the name
argument is slugified and turned into the id for the submit button.
By default None.
css_class : str, optional
Additional CSS classes to be applied to the ``<input>``. By default
None.
template : str, optional
Overrides the default template, if provided. By default None.
**kwargs : dict, optional
Additional attributes are passed to `flatatt` and converted into
key="value", pairs. These attributes are added to the ``<input>``.
Examples
--------
Note: ``form`` arg to ``render()`` is not required for ``BaseInput``
inherited objects.
>>> submit = Submit('Search the Site', 'search this site')
>>> submit.render("", "", Context())
'<input type="submit" name="search-the-site" value="search this site" '
'class="btn btn-primary" id="submit-id-search-the-site"/>'
>>> submit = Submit('Search the Site', 'search this site', css_id="custom-id",
css_class="custom class", my_attr=True, data="my-data")
>>> submit.render("", "", Context())
'<input type="submit" name="search-the-site" value="search this site" '
'class="btn btn-primary custom class" id="custom-id" data="my-data" my-attr/>'
Usually you will not call the render method on the object directly. Instead
add it to your ``Layout`` manually or use the `add_input` method::
class ExampleForm(forms.Form):
[...]
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.add_input(Submit('submit', 'Submit'))
"""
input_type = "submit"
field_classes = "btn btn-primary"
| Submit |
python | redis__redis-py | redis/cluster.py | {
"start": 88599,
"end": 97983
} | class ____(RedisCluster):
"""
Support for Redis pipeline
in cluster mode
"""
ERRORS_ALLOW_RETRY = (
ConnectionError,
TimeoutError,
MovedError,
AskError,
TryAgainError,
)
NO_SLOTS_COMMANDS = {"UNWATCH"}
IMMEDIATE_EXECUTE_COMMANDS = {"WATCH", "UNWATCH"}
UNWATCH_COMMANDS = {"DISCARD", "EXEC", "UNWATCH"}
@deprecated_args(
args_to_warn=[
"cluster_error_retry_attempts",
],
reason="Please configure the 'retry' object instead",
version="6.0.0",
)
def __init__(
self,
nodes_manager: "NodesManager",
commands_parser: "CommandsParser",
result_callbacks: Optional[Dict[str, Callable]] = None,
cluster_response_callbacks: Optional[Dict[str, Callable]] = None,
startup_nodes: Optional[List["ClusterNode"]] = None,
read_from_replicas: bool = False,
load_balancing_strategy: Optional[LoadBalancingStrategy] = None,
cluster_error_retry_attempts: int = 3,
reinitialize_steps: int = 5,
retry: Optional[Retry] = None,
lock=None,
transaction=False,
policy_resolver: PolicyResolver = StaticPolicyResolver(),
**kwargs,
):
""" """
self.command_stack = []
self.nodes_manager = nodes_manager
self.commands_parser = commands_parser
self.refresh_table_asap = False
self.result_callbacks = (
result_callbacks or self.__class__.RESULT_CALLBACKS.copy()
)
self.startup_nodes = startup_nodes if startup_nodes else []
self.read_from_replicas = read_from_replicas
self.load_balancing_strategy = load_balancing_strategy
self.command_flags = self.__class__.COMMAND_FLAGS.copy()
self.cluster_response_callbacks = cluster_response_callbacks
self.reinitialize_counter = 0
self.reinitialize_steps = reinitialize_steps
if retry is not None:
self.retry = retry
else:
self.retry = Retry(
backoff=ExponentialWithJitterBackoff(base=1, cap=10),
retries=cluster_error_retry_attempts,
)
self.encoder = Encoder(
kwargs.get("encoding", "utf-8"),
kwargs.get("encoding_errors", "strict"),
kwargs.get("decode_responses", False),
)
if lock is None:
lock = threading.RLock()
self._lock = lock
self.parent_execute_command = super().execute_command
self._execution_strategy: ExecutionStrategy = (
PipelineStrategy(self) if not transaction else TransactionStrategy(self)
)
# For backward compatibility, mapping from existing policies to new one
self._command_flags_mapping: dict[str, Union[RequestPolicy, ResponsePolicy]] = {
self.__class__.RANDOM: RequestPolicy.DEFAULT_KEYLESS,
self.__class__.PRIMARIES: RequestPolicy.ALL_SHARDS,
self.__class__.ALL_NODES: RequestPolicy.ALL_NODES,
self.__class__.REPLICAS: RequestPolicy.ALL_REPLICAS,
self.__class__.DEFAULT_NODE: RequestPolicy.DEFAULT_NODE,
SLOT_ID: RequestPolicy.DEFAULT_KEYED,
}
self._policies_callback_mapping: dict[
Union[RequestPolicy, ResponsePolicy], Callable
] = {
RequestPolicy.DEFAULT_KEYLESS: lambda command_name: [
self.get_random_primary_or_all_nodes(command_name)
],
RequestPolicy.DEFAULT_KEYED: lambda command,
*args: self.get_nodes_from_slot(command, *args),
RequestPolicy.DEFAULT_NODE: lambda: [self.get_default_node()],
RequestPolicy.ALL_SHARDS: self.get_primaries,
RequestPolicy.ALL_NODES: self.get_nodes,
RequestPolicy.ALL_REPLICAS: self.get_replicas,
RequestPolicy.MULTI_SHARD: lambda *args,
**kwargs: self._split_multi_shard_command(*args, **kwargs),
RequestPolicy.SPECIAL: self.get_special_nodes,
ResponsePolicy.DEFAULT_KEYLESS: lambda res: res,
ResponsePolicy.DEFAULT_KEYED: lambda res: res,
}
self._policy_resolver = policy_resolver
def __repr__(self):
""" """
return f"{type(self).__name__}"
def __enter__(self):
""" """
return self
def __exit__(self, exc_type, exc_value, traceback):
""" """
self.reset()
def __del__(self):
try:
self.reset()
except Exception:
pass
def __len__(self):
""" """
return len(self._execution_strategy.command_queue)
def __bool__(self):
"Pipeline instances should always evaluate to True on Python 3+"
return True
def execute_command(self, *args, **kwargs):
"""
Wrapper function for pipeline_execute_command
"""
return self._execution_strategy.execute_command(*args, **kwargs)
def pipeline_execute_command(self, *args, **options):
"""
Stage a command to be executed when execute() is next called
Returns the current Pipeline object back so commands can be
chained together, such as:
pipe = pipe.set('foo', 'bar').incr('baz').decr('bang')
At some other point, you can then run: pipe.execute(),
which will execute all commands queued in the pipe.
"""
return self._execution_strategy.execute_command(*args, **options)
def annotate_exception(self, exception, number, command):
"""
Provides extra context to the exception prior to it being handled
"""
self._execution_strategy.annotate_exception(exception, number, command)
def execute(self, raise_on_error: bool = True) -> List[Any]:
"""
Execute all the commands in the current pipeline
"""
try:
return self._execution_strategy.execute(raise_on_error)
finally:
self.reset()
def reset(self):
"""
Reset back to empty pipeline.
"""
self._execution_strategy.reset()
def send_cluster_commands(
self, stack, raise_on_error=True, allow_redirections=True
):
return self._execution_strategy.send_cluster_commands(
stack, raise_on_error=raise_on_error, allow_redirections=allow_redirections
)
def exists(self, *keys):
return self._execution_strategy.exists(*keys)
def eval(self):
""" """
return self._execution_strategy.eval()
def multi(self):
"""
Start a transactional block of the pipeline after WATCH commands
are issued. End the transactional block with `execute`.
"""
self._execution_strategy.multi()
def load_scripts(self):
""" """
self._execution_strategy.load_scripts()
def discard(self):
""" """
self._execution_strategy.discard()
def watch(self, *names):
"""Watches the values at keys ``names``"""
self._execution_strategy.watch(*names)
def unwatch(self):
"""Unwatches all previously specified keys"""
self._execution_strategy.unwatch()
def script_load_for_pipeline(self, *args, **kwargs):
self._execution_strategy.script_load_for_pipeline(*args, **kwargs)
def delete(self, *names):
self._execution_strategy.delete(*names)
def unlink(self, *names):
self._execution_strategy.unlink(*names)
def block_pipeline_command(name: str) -> Callable[..., Any]:
"""
Prints error because some pipelined commands should
be blocked when running in cluster-mode
"""
def inner(*args, **kwargs):
raise RedisClusterException(
f"ERROR: Calling pipelined function {name} is blocked "
f"when running redis in cluster mode..."
)
return inner
# Blocked pipeline commands
PIPELINE_BLOCKED_COMMANDS = (
"BGREWRITEAOF",
"BGSAVE",
"BITOP",
"BRPOPLPUSH",
"CLIENT GETNAME",
"CLIENT KILL",
"CLIENT LIST",
"CLIENT SETNAME",
"CLIENT",
"CONFIG GET",
"CONFIG RESETSTAT",
"CONFIG REWRITE",
"CONFIG SET",
"CONFIG",
"DBSIZE",
"ECHO",
"EVALSHA",
"FLUSHALL",
"FLUSHDB",
"INFO",
"KEYS",
"LASTSAVE",
"MGET",
"MGET NONATOMIC",
"MOVE",
"MSET",
"MSETEX",
"MSET NONATOMIC",
"MSETNX",
"PFCOUNT",
"PFMERGE",
"PING",
"PUBLISH",
"RANDOMKEY",
"READONLY",
"READWRITE",
"RENAME",
"RENAMENX",
"RPOPLPUSH",
"SAVE",
"SCAN",
"SCRIPT EXISTS",
"SCRIPT FLUSH",
"SCRIPT KILL",
"SCRIPT LOAD",
"SCRIPT",
"SDIFF",
"SDIFFSTORE",
"SENTINEL GET MASTER ADDR BY NAME",
"SENTINEL MASTER",
"SENTINEL MASTERS",
"SENTINEL MONITOR",
"SENTINEL REMOVE",
"SENTINEL SENTINELS",
"SENTINEL SET",
"SENTINEL SLAVES",
"SENTINEL",
"SHUTDOWN",
"SINTER",
"SINTERSTORE",
"SLAVEOF",
"SLOWLOG GET",
"SLOWLOG LEN",
"SLOWLOG RESET",
"SLOWLOG",
"SMOVE",
"SORT",
"SUNION",
"SUNIONSTORE",
"TIME",
)
for command in PIPELINE_BLOCKED_COMMANDS:
command = command.replace(" ", "_").lower()
setattr(ClusterPipeline, command, block_pipeline_command(command))
| ClusterPipeline |
python | mahmoud__boltons | boltons/deprutils.py | {
"start": 1606,
"end": 2478
} | class ____(ModuleType):
def __init__(self, module):
name = module.__name__
super().__init__(name=name)
self.__dict__.update(module.__dict__)
def __getattribute__(self, name):
get_attribute = super().__getattribute__
try:
depros = get_attribute('_deprecated_members')
except AttributeError:
self._deprecated_members = depros = {}
ret = get_attribute(name)
message = depros.get(name)
if message is not None:
warn(message, DeprecationWarning, stacklevel=2)
return ret
def deprecate_module_member(mod_name, name, message):
module = sys.modules[mod_name]
if not isinstance(module, DeprecatableModule):
sys.modules[mod_name] = module = DeprecatableModule(module)
module._deprecated_members[name] = message
return
| DeprecatableModule |
python | falconry__falcon | tests/test_before_hooks.py | {
"start": 5486,
"end": 5645
} | class ____:
def on_get(self, req, resp, bunnies, frogs, fish):
self.bunnies = bunnies
self.frogs = frogs
self.fish = fish
| ZooResource |
python | ray-project__ray | rllib/models/torch/modules/relative_multi_head_attention.py | {
"start": 1452,
"end": 6336
} | class ____(nn.Module):
"""A RelativeMultiHeadAttention layer as described in [3].
Uses segment level recurrence with state reuse.
"""
def __init__(
self,
in_dim: int,
out_dim: int,
num_heads: int,
head_dim: int,
input_layernorm: bool = False,
output_activation: Union[str, callable] = None,
**kwargs
):
"""Initializes a RelativeMultiHeadAttention nn.Module object.
Args:
in_dim (int):
out_dim: The output dimension of this module. Also known as
"attention dim".
num_heads: The number of attention heads to use.
Denoted `H` in [2].
head_dim: The dimension of a single(!) attention head
Denoted `D` in [2].
input_layernorm: Whether to prepend a LayerNorm before
everything else. Should be True for building a GTrXL.
output_activation (Union[str, callable]): Optional activation
function or activation function specifier (str).
Should be "relu" for GTrXL.
**kwargs:
"""
super().__init__(**kwargs)
# No bias or non-linearity.
self._num_heads = num_heads
self._head_dim = head_dim
# 3=Query, key, and value inputs.
self._qkv_layer = SlimFC(
in_size=in_dim, out_size=3 * num_heads * head_dim, use_bias=False
)
self._linear_layer = SlimFC(
in_size=num_heads * head_dim,
out_size=out_dim,
use_bias=False,
activation_fn=output_activation,
)
self._uvar = nn.Parameter(torch.zeros(num_heads, head_dim))
self._vvar = nn.Parameter(torch.zeros(num_heads, head_dim))
nn.init.xavier_uniform_(self._uvar)
nn.init.xavier_uniform_(self._vvar)
self.register_parameter("_uvar", self._uvar)
self.register_parameter("_vvar", self._vvar)
self._pos_proj = SlimFC(
in_size=in_dim, out_size=num_heads * head_dim, use_bias=False
)
self._rel_pos_embedding = RelativePositionEmbedding(out_dim)
self._input_layernorm = None
if input_layernorm:
self._input_layernorm = torch.nn.LayerNorm(in_dim)
def forward(self, inputs: TensorType, memory: TensorType = None) -> TensorType:
T = list(inputs.size())[1] # length of segment (time)
H = self._num_heads # number of attention heads
d = self._head_dim # attention head dimension
# Add previous memory chunk (as const, w/o gradient) to input.
# Tau (number of (prev) time slices in each memory chunk).
Tau = list(memory.shape)[1]
inputs = torch.cat((memory.detach(), inputs), dim=1)
# Apply the Layer-Norm.
if self._input_layernorm is not None:
inputs = self._input_layernorm(inputs)
qkv = self._qkv_layer(inputs)
queries, keys, values = torch.chunk(input=qkv, chunks=3, dim=-1)
# Cut out Tau memory timesteps from query.
queries = queries[:, -T:]
queries = torch.reshape(queries, [-1, T, H, d])
keys = torch.reshape(keys, [-1, Tau + T, H, d])
values = torch.reshape(values, [-1, Tau + T, H, d])
R = self._pos_proj(self._rel_pos_embedding(Tau + T))
R = torch.reshape(R, [Tau + T, H, d])
# b=batch
# i and j=time indices (i=max-timesteps (inputs); j=Tau memory space)
# h=head
# d=head-dim (over which we will reduce-sum)
score = torch.einsum("bihd,bjhd->bijh", queries + self._uvar, keys)
pos_score = torch.einsum("bihd,jhd->bijh", queries + self._vvar, R)
score = score + self.rel_shift(pos_score)
score = score / d**0.5
# causal mask of the same length as the sequence
mask = sequence_mask(torch.arange(Tau + 1, Tau + T + 1), dtype=score.dtype).to(
score.device
)
mask = mask[None, :, :, None]
masked_score = score * mask + 1e30 * (mask.float() - 1.0)
wmat = nn.functional.softmax(masked_score, dim=2)
out = torch.einsum("bijh,bjhd->bihd", wmat, values)
shape = list(out.shape)[:2] + [H * d]
out = torch.reshape(out, shape)
return self._linear_layer(out)
@staticmethod
def rel_shift(x: TensorType) -> TensorType:
# Transposed version of the shift approach described in [3].
# https://github.com/kimiyoung/transformer-xl/blob/
# 44781ed21dbaec88b280f74d9ae2877f52b492a5/tf/model.py#L31
x_size = list(x.shape)
x = torch.nn.functional.pad(x, (0, 0, 1, 0, 0, 0, 0, 0))
x = torch.reshape(x, [x_size[0], x_size[2] + 1, x_size[1], x_size[3]])
x = x[:, 1:, :, :]
x = torch.reshape(x, x_size)
return x
| RelativeMultiHeadAttention |
python | pytorch__pytorch | torch/nn/modules/loss.py | {
"start": 63589,
"end": 66249
} | class ____(_WeightedLoss):
r"""Creates a criterion that optimizes a multi-label one-versus-all
loss based on max-entropy, between input :math:`x` and target :math:`y` of size
:math:`(N, C)`.
For each sample in the minibatch:
.. math::
loss(x, y) = - \frac{1}{C} * \sum_i y[i] * \log((1 + \exp(-x[i]))^{-1})
+ (1-y[i]) * \log\left(\frac{\exp(-x[i])}{(1 + \exp(-x[i]))}\right)
where :math:`i \in \left\{0, \; \cdots , \; \text{x.nElement}() - 1\right\}`,
:math:`y[i] \in \left\{0, \; 1\right\}`.
Args:
weight (Tensor, optional): a manual rescaling weight given to each
class. If given, it has to be a Tensor of size `C`. Otherwise, it is
treated as if having all ones.
size_average (bool, optional): Deprecated (see :attr:`reduction`). By default,
the losses are averaged over each loss element in the batch. Note that for
some losses, there are multiple elements per sample. If the field :attr:`size_average`
is set to ``False``, the losses are instead summed for each minibatch. Ignored
when :attr:`reduce` is ``False``. Default: ``True``
reduce (bool, optional): Deprecated (see :attr:`reduction`). By default, the
losses are averaged or summed over observations for each minibatch depending
on :attr:`size_average`. When :attr:`reduce` is ``False``, returns a loss per
batch element instead and ignores :attr:`size_average`. Default: ``True``
reduction (str, optional): Specifies the reduction to apply to the output:
``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction will be applied,
``'mean'``: the sum of the output will be divided by the number of
elements in the output, ``'sum'``: the output will be summed. Note: :attr:`size_average`
and :attr:`reduce` are in the process of being deprecated, and in the meantime,
specifying either of those two args will override :attr:`reduction`. Default: ``'mean'``
Shape:
- Input: :math:`(N, C)` where `N` is the batch size and `C` is the number of classes.
- Target: :math:`(N, C)`, label targets must have the same shape as the input.
- Output: scalar. If :attr:`reduction` is ``'none'``, then :math:`(N)`.
"""
__constants__ = ["reduction"]
def forward(self, input: Tensor, target: Tensor) -> Tensor:
"""Runs the forward pass."""
return F.multilabel_soft_margin_loss(
input, target, weight=self.weight, reduction=self.reduction
)
| MultiLabelSoftMarginLoss |
python | getsentry__sentry | src/sentry/integrations/repository/metric_alert.py | {
"start": 2808,
"end": 5498
} | class ____:
"""
Repository class that is responsible for querying the data store for notification messages in relation to metric
alerts.
"""
_model = NotificationMessage
def __init__(self, logger: Logger) -> None:
self._logger: Logger = logger
@classmethod
def default(cls) -> MetricAlertNotificationMessageRepository:
return cls(logger=_default_logger)
def get_parent_notification_message(
self, alert_rule_id: int, incident_id: int, trigger_action_id: int
) -> MetricAlertNotificationMessage | None:
"""
Returns the parent notification message for a metric rule if it exists, otherwise returns None.
Will raise an exception if the query fails and logs the error with associated data.
"""
try:
instance: NotificationMessage = self._model.objects.get(
incident__alert_rule__id=alert_rule_id,
incident__id=incident_id,
trigger_action__id=trigger_action_id,
parent_notification_message__isnull=True,
error_code__isnull=True,
)
return MetricAlertNotificationMessage.from_model(instance=instance)
except NotificationMessage.DoesNotExist:
return None
except Exception as e:
self._logger.exception(
"Failed to get parent notification for metric rule",
exc_info=e,
extra={
"incident_id": incident_id,
"alert_rule_id": alert_rule_id,
"trigger_action_id": trigger_action_id,
},
)
raise
def create_notification_message(
self, data: NewMetricAlertNotificationMessage
) -> MetricAlertNotificationMessage:
if (error := data.get_validation_error()) is not None:
raise error
try:
new_instance = self._model.objects.create(
error_details=data.error_details,
error_code=data.error_code,
message_identifier=data.message_identifier,
parent_notification_message_id=data.parent_notification_message_id,
incident_id=data.incident_id,
trigger_action_id=data.trigger_action_id,
)
return MetricAlertNotificationMessage.from_model(instance=new_instance)
except Exception as e:
self._logger.exception(
"failed to create new metric alert notification alert",
exc_info=e,
extra=data.__dict__,
)
raise
| MetricAlertNotificationMessageRepository |
python | Pylons__pyramid | tests/test_asset.py | {
"start": 1517,
"end": 2173
} | class ____(unittest.TestCase):
def _callFUT(self, spec, pname='__main__'):
from pyramid.resource import abspath_from_asset_spec
return abspath_from_asset_spec(spec, pname)
def test_pname_is_None_before_resolve_asset_spec(self):
result = self._callFUT('abc', None)
self.assertEqual(result, 'abc')
def test_pname_is_None_after_resolve_asset_spec(self):
result = self._callFUT('/abc', '__main__')
self.assertEqual(result, '/abc')
def test_pkgrelative(self):
result = self._callFUT('abc', 'tests')
self.assertEqual(result, os.path.join(here, 'abc'))
| Test_abspath_from_asset_spec |
python | dask__dask | dask/_expr.py | {
"start": 28943,
"end": 32716
} | class ____(Expr):
_parameters = [
"dsk",
"low_level_optimizer",
"output_keys",
"postcompute",
"_cached_optimized",
]
_defaults = {
"low_level_optimizer": None,
"output_keys": None,
"postcompute": None,
"_cached_optimized": None,
}
@property
def hlg(self):
return self.operand("dsk")
@staticmethod
def from_collection(collection, optimize_graph=True):
from dask.highlevelgraph import HighLevelGraph
if hasattr(collection, "dask"):
dsk = collection.dask.copy()
else:
dsk = collection.__dask_graph__()
# Delayed objects still ship with low level graphs as `dask` when going
# through optimize / persist
if not isinstance(dsk, HighLevelGraph):
dsk = HighLevelGraph.from_collections(
str(id(collection)), dsk, dependencies=()
)
if optimize_graph and not hasattr(collection, "__dask_optimize__"):
warnings.warn(
f"Collection {type(collection)} does not define a "
"`__dask_optimize__` method. In the future this will raise. "
"If no optimization is desired, please set this to `None`.",
PendingDeprecationWarning,
)
low_level_optimizer = None
else:
low_level_optimizer = (
collection.__dask_optimize__ if optimize_graph else None
)
return HLGExpr(
dsk=dsk,
low_level_optimizer=low_level_optimizer,
output_keys=collection.__dask_keys__(),
postcompute=collection.__dask_postcompute__(),
)
def finalize_compute(self):
return HLGFinalizeCompute(
self,
low_level_optimizer=self.low_level_optimizer,
output_keys=self.output_keys,
postcompute=self.postcompute,
)
def __dask_annotations__(self) -> dict[str, dict[Key, object]]:
# optimization has to be called (and cached) since blockwise fusion can
# alter annotations
# see `dask.blockwise.(_fuse_annotations|_can_fuse_annotations)`
dsk = self._optimized_dsk
annotations_by_type: defaultdict[str, dict[Key, object]] = defaultdict(dict)
for layer in dsk.layers.values():
if layer.annotations:
annot = layer.annotations
for annot_type, value in annot.items():
annotations_by_type[annot_type].update(
{k: (value(k) if callable(value) else value) for k in layer}
)
return dict(annotations_by_type)
def __dask_keys__(self):
if (keys := self.operand("output_keys")) is not None:
return keys
dsk = self.hlg
# Note: This will materialize
dependencies = dsk.get_all_dependencies()
leafs = set(dependencies)
for val in dependencies.values():
leafs -= val
self.output_keys = list(leafs)
return self.output_keys
@functools.cached_property
def _optimized_dsk(self) -> HighLevelGraph:
from dask.highlevelgraph import HighLevelGraph
optimizer = self.low_level_optimizer
keys = self.__dask_keys__()
dsk = self.hlg
if (optimizer := self.low_level_optimizer) is not None:
dsk = optimizer(dsk, keys)
return HighLevelGraph.merge(dsk)
@property
def deterministic_token(self):
if not self._determ_token:
self._determ_token = uuid.uuid4().hex
return self._determ_token
def _layer(self) -> dict:
dsk = self._optimized_dsk
return ensure_dict(dsk)
| HLGExpr |
python | ray-project__ray | python/ray/tune/search/sample.py | {
"start": 4634,
"end": 4722
} | class ____(Sampler):
def __str__(self):
return "Uniform"
@DeveloperAPI
| Uniform |
python | google__pytype | pytype/abstract/_instances.py | {
"start": 2203,
"end": 2660
} | class ____(_instance_base.Instance, mixin.PythonConstant):
"""Abstract value with a concrete fallback."""
def __init__(
self,
pyval: _base.BaseValue | None,
cls: _instance_base.SimpleValue,
ctx: "context.Context",
) -> None:
super().__init__(cls, ctx)
mixin.PythonConstant.init_mixin(self, pyval)
def get_fullhash(self, seen: set[int] | None = None) -> int:
return hash((type(self), id(self.pyval)))
| ConcreteValue |
python | chroma-core__chroma | chromadb/api/types.py | {
"start": 57190,
"end": 58675
} | class ____(BaseModel):
"""Configuration for boolean inverted index."""
model_config = {"extra": "forbid"}
pass
# Union type for all index configurations (used by new Schema class)
IndexConfig: TypeAlias = Union[
FtsIndexConfig,
VectorIndexConfig,
SparseVectorIndexConfig,
StringInvertedIndexConfig,
IntInvertedIndexConfig,
FloatInvertedIndexConfig,
BoolInvertedIndexConfig,
]
# Value type constants
STRING_VALUE_NAME: Final[str] = "string"
INT_VALUE_NAME: Final[str] = "int"
BOOL_VALUE_NAME: Final[str] = "bool"
FLOAT_VALUE_NAME: Final[str] = "float"
FLOAT_LIST_VALUE_NAME: Final[str] = "float_list"
SPARSE_VECTOR_VALUE_NAME: Final[str] = "sparse_vector"
# Index type name constants
FTS_INDEX_NAME: Final[str] = "fts_index"
VECTOR_INDEX_NAME: Final[str] = "vector_index"
SPARSE_VECTOR_INDEX_NAME: Final[str] = "sparse_vector_index"
STRING_INVERTED_INDEX_NAME: Final[str] = "string_inverted_index"
INT_INVERTED_INDEX_NAME: Final[str] = "int_inverted_index"
FLOAT_INVERTED_INDEX_NAME: Final[str] = "float_inverted_index"
BOOL_INVERTED_INDEX_NAME: Final[str] = "bool_inverted_index"
HNSW_INDEX_NAME: Final[str] = "hnsw_index"
SPANN_INDEX_NAME: Final[str] = "spann_index"
# Special key constants
DOCUMENT_KEY: Final[str] = "#document"
EMBEDDING_KEY: Final[str] = "#embedding"
TYPE_KEY: Final[str] = "#type"
# Type value constants
SPARSE_VECTOR_TYPE_VALUE: Final[str] = "sparse_vector"
# Index Type Classes
@dataclass
| BoolInvertedIndexConfig |
python | sympy__sympy | sympy/integrals/manualintegrate.py | {
"start": 7722,
"end": 7869
} | class ____(TrigRule):
"""integrate(csc(x)**2, x) -> -cot(x)"""
def eval(self) -> Expr:
return -cot(self.variable)
@dataclass
| Csc2Rule |
python | pytorch__pytorch | test/distributed/test_c10d_common.py | {
"start": 4307,
"end": 6747
} | class ____(TestCase):
@retry_on_connect_failures
def test_store_based_barrier(self):
f = tempfile.NamedTemporaryFile(delete=False)
port = common.find_free_port()
def thread_work(timeout, init_type, world_size, rank, error_list):
# we need to create a separate store just for the store barrier test
if init_type == "file":
barrier_store = dist.FileStore(f.name)
elif init_type == "tcp":
barrier_store = dist.TCPStore(
"localhost",
port,
world_size,
is_master=rank == 0,
wait_for_workers=False,
)
elif init_type == "hash":
barrier_store = dist.HashStore()
try:
# 1 missing worker will cause it to timeout
if rank != world_size - 1:
c10d._store_based_barrier(
rank=rank,
store=barrier_store,
group_name="_",
rendezvous_count=world_size,
timeout=timeout,
logging_interval=timeout / 2,
)
except torch.distributed.DistStoreError as e:
self.assertTrue(isinstance(e, torch.distributed.DistError))
error_list.append(e)
world_size = 4
error_list = []
threads = []
for init_type in ["file", "tcp", "hash"]:
for rank in range(world_size):
t = threading.Thread(
target=thread_work,
args=(
timedelta(seconds=3),
init_type,
world_size,
rank,
error_list,
),
)
threads.append(t)
t.start()
for thread in threads:
thread.join()
# we expect the world_size-1 threads to have failed
self.assertEqual(len(error_list), world_size - 1)
for error in error_list:
self.assertTrue(
"Timed out initializing process group in store based barrier"
in error.args[0]
)
error_list = []
threads = []
| TimeoutTest |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/logs/events.py | {
"start": 2664,
"end": 2806
} | class ____(graphene.Interface):
pipelineName = graphene.NonNull(graphene.String)
class Meta:
name = "RunEvent"
| GrapheneRunEvent |
python | django__django | tests/flatpages_tests/test_views.py | {
"start": 289,
"end": 2462
} | class ____:
@classmethod
def setUpTestData(cls):
# don't use the manager because we want to ensure the site exists
# with pk=1, regardless of whether or not it already exists.
cls.site1 = Site(pk=1, domain="example.com", name="example.com")
cls.site1.save()
cls.fp1 = FlatPage.objects.create(
url="/flatpage/",
title="A Flatpage",
content="Isn't it flat!",
enable_comments=False,
template_name="",
registration_required=False,
)
cls.fp2 = FlatPage.objects.create(
url="/location/flatpage/",
title="A Nested Flatpage",
content="Isn't it flat and deep!",
enable_comments=False,
template_name="",
registration_required=False,
)
cls.fp3 = FlatPage.objects.create(
url="/sekrit/",
title="Sekrit Flatpage",
content="Isn't it sekrit!",
enable_comments=False,
template_name="",
registration_required=True,
)
cls.fp4 = FlatPage.objects.create(
url="/location/sekrit/",
title="Sekrit Nested Flatpage",
content="Isn't it sekrit and deep!",
enable_comments=False,
template_name="",
registration_required=True,
)
cls.fp1.sites.add(cls.site1)
cls.fp2.sites.add(cls.site1)
cls.fp3.sites.add(cls.site1)
cls.fp4.sites.add(cls.site1)
@modify_settings(INSTALLED_APPS={"append": "django.contrib.flatpages"})
@override_settings(
LOGIN_URL="/accounts/login/",
MIDDLEWARE=[
"django.middleware.common.CommonMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
# no 'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware'
],
ROOT_URLCONF="flatpages_tests.urls",
TEMPLATES=FLATPAGES_TEMPLATES,
SITE_ID=1,
)
| TestDataMixin |
python | getsentry__sentry | src/sentry/api/endpoints/project_rule_preview.py | {
"start": 900,
"end": 2887
} | class ____(ProjectEndpoint):
owner = ApiOwner.ISSUES
publish_status = {
"POST": ApiPublishStatus.PRIVATE,
}
permission_classes = (ProjectAlertRulePermission,)
# a post endpoint because it's too hard to pass a list of objects from the frontend
def post(self, request: Request, project) -> Response:
"""
Get a list of alert triggers in past 2 weeks for given rules
{method} {path}
{{
"conditions": [],
"filters": [],
"actionMatch": "all",
"filterMatch": "all",
"frequency": 60,
"endpoint": datetime or None
}}
"""
serializer = RulePreviewSerializer(
context={"project": project, "organization": project.organization}, data=request.data
)
if not serializer.is_valid():
raise ValidationError
data = serializer.validated_data
if data.get("endpoint") is None:
data["endpoint"] = timezone.now()
group_fires = preview(
project,
data.get("conditions", []),
data.get("filters", []),
data.get("actionMatch"),
data.get("filterMatch"),
data.get("frequency"),
data.get("endpoint"),
)
if group_fires is None:
raise ValidationError
fired_groups = Group.objects.filter(id__in=group_fires.keys()).order_by("-id")
response = self.paginate(
request=request,
queryset=fired_groups,
order_by="-id",
count_hits=True,
)
response.data = serialize(
response.data,
request.user,
PreviewSerializer(),
inbox_details=get_inbox_details(response.data),
group_fires=group_fires,
)
response["Endpoint"] = data["endpoint"]
return response
| ProjectRulePreviewEndpoint |
python | dagster-io__dagster | examples/assets_pandas_type_metadata/assets_pandas_type_metadata/assets/bollinger_analysis.py | {
"start": 445,
"end": 1267
} | class ____(Config):
rate: int = Field(default=30, description="Size of sliding window in days")
sigma: float = Field(default=2.0, description="Width of envelope in standard deviations")
@asset(
dagster_type=BollingerBandsDgType,
metadata={"owner": "alice@example.com"},
)
def sp500_bollinger_bands(config: BollingerBandsConfig, sp500_prices):
"""Bollinger bands for the S&P 500 stock prices."""
return compute_bollinger_bands_multi(sp500_prices, rate=config.rate, sigma=config.sigma)
@asset(
dagster_type=AnomalousEventsDgType,
metadata={"owner": "alice@example.com"},
)
def sp500_anomalous_events(sp500_prices, sp500_bollinger_bands):
"""Anomalous events for the S&P 500 stock prices."""
return compute_anomalous_events(sp500_prices, sp500_bollinger_bands)
| BollingerBandsConfig |
python | PyCQA__pylint | pylint/config/callback_actions.py | {
"start": 4619,
"end": 5067
} | class ____(_AccessRunObjectAction):
"""Display all the check groups that pylint knows about."""
def __call__(
self,
parser: argparse.ArgumentParser,
namespace: argparse.Namespace,
values: str | Sequence[Any] | None,
option_string: str | None = "--list-groups",
) -> None:
for check in self.run.linter.get_checker_names():
print(check)
sys.exit(0)
| _ListCheckGroupsAction |
python | walkccc__LeetCode | solutions/3002. Maximum Size of a Set After Removals/3002.py | {
"start": 0,
"end": 387
} | class ____:
def maximumSetSize(self, nums1: list[int], nums2: list[int]) -> int:
set1 = set(nums1)
set2 = set(nums2)
common = set1.intersection(set2)
n = len(nums1)
n1 = len(set1)
n2 = len(set2)
nc = len(common)
maxUniqueNums1 = min(n1 - nc, n // 2)
maxUniqueNums2 = min(n2 - nc, n // 2)
return min(n, maxUniqueNums1 + maxUniqueNums2 + nc)
| Solution |
python | pytorch__pytorch | test/dynamo/test_higher_order_ops.py | {
"start": 12629,
"end": 14149
} | class ____(torch.nn.Module):
def forward(self, L_d_x_: "f32[]", L_d_y_0_: "f32[]", L_d_y_1_2_: "f32[]"):
l_d_x_ = L_d_x_
l_d_y_0_ = L_d_y_0_
l_d_y_1_2_ = L_d_y_1_2_
wrap_body_0 = self.wrap_body_0
wrap = torch.ops.higher_order.wrap(wrap_body_0, l_d_x_, l_d_y_0_, l_d_y_1_2_); wrap_body_0 = l_d_x_ = l_d_y_0_ = l_d_y_1_2_ = None
getitem: "f32[]" = wrap[0]; wrap = None
return (getitem,)
class wrap_body_0(torch.nn.Module):
def forward(self, l_d_x_: "f32[]", l_d_y_0_: "f32[]", l_d_y_1_2_: "f32[]"):
sin: "f32[]" = l_d_x_.sin(); l_d_x_ = None
cos: "f32[]" = l_d_y_0_.cos(); l_d_y_0_ = None
add: "f32[]" = sin + cos; sin = cos = None
sin_1: "f32[]" = l_d_y_1_2_.sin(); l_d_y_1_2_ = None
sub: "f32[]" = add - sin_1; add = sin_1 = None
return (sub,)
""", # NOQA: B950
)
def test_wrap_pytree_args_with_symint_constant(self):
def f(x, y):
i = x.size(0)
return wrap(lambda t: t[0].view(t[2]) + t[1], (x, y, i))
x = torch.randn(3, 1)
y = 0.5
actual_graph = self._test_wrap_simple(
f,
default_args_generator((x, y)),
ifdynstaticdefault(2, 3),
expected_opcount=2,
return_graph=True,
)
if torch._dynamo.config.assume_static_by_default:
self.assertExpectedInline(
actual_graph,
"""\
| GraphModule |
python | huggingface__transformers | tests/models/cohere2/test_modeling_cohere2.py | {
"start": 1630,
"end": 1838
} | class ____(CohereModelTester):
config_class = Cohere2Config
if is_torch_available():
model_class = Cohere2Model
for_causal_lm_class = Cohere2ForCausalLM
@require_torch
| Cohere2ModelTester |
python | getsentry__sentry | src/sentry/sentry_apps/api/serializers/app_platform_event.py | {
"start": 964,
"end": 3082
} | class ____[T: Mapping[str, Any]]():
"""
This data structure encapsulates the payload sent to a SentryApp's webhook.
The data field is generic and should be typed with a TypedDict specified by the user.
"""
def __init__(
self,
resource: SentryAppResourceType,
action: SentryAppActionType,
install: RpcSentryAppInstallation | SentryAppInstallation,
data: T,
actor: RpcUser | User | None = None,
):
self.resource = resource
self.action = action
self.install = install
self.data = data
self.actor = actor
def get_actor(self) -> AppPlatformEventActor:
# when sentry auto assigns, auto resolves, etc.
# or when an alert rule is triggered
if not self.actor:
return AppPlatformEventActor(
type=AppPlatformEventActorType.APPLICATION,
id="sentry",
name="Sentry",
)
if self.actor.is_sentry_app:
return AppPlatformEventActor(
type=AppPlatformEventActorType.APPLICATION,
id=self.install.sentry_app.uuid,
name=self.install.sentry_app.name,
)
return AppPlatformEventActor(
type=AppPlatformEventActorType.USER,
id=self.actor.id,
name=self.actor.name,
)
@property
def body(self) -> str:
return json.dumps(
AppPlatformEventBody(
action=self.action,
installation=AppPlatformEventInstallation(uuid=self.install.uuid),
data=self.data,
actor=self.get_actor(),
)
)
@property
def headers(self) -> dict[str, str]:
request_uuid = uuid4().hex
return {
"Content-Type": "application/json",
"Request-ID": request_uuid,
"Sentry-Hook-Resource": self.resource,
"Sentry-Hook-Timestamp": str(int(time())),
"Sentry-Hook-Signature": self.install.sentry_app.build_signature(self.body),
}
| AppPlatformEvent |
python | getsentry__sentry | src/sentry/snuba/metrics/fields/base.py | {
"start": 10137,
"end": 11085
} | class ____(AliasedDerivedMetricDefinition, MetricObject):
"""
Represents a class where metric object is a class that encapsulates filter logic on an alias
for a raw metric name
"""
def generate_metric_ids(self, projects: Sequence[Project], use_case_id: UseCaseID) -> set[int]:
return {resolve_weak(use_case_id, org_id_from_projects(projects), self.raw_metric_mri)}
def generate_filter_snql_conditions(self, org_id: int, use_case_id: UseCaseID) -> Function:
conditions = [
Function(
"equals",
[
Column("metric_id"),
resolve_weak(use_case_id, org_id, self.raw_metric_mri),
],
)
]
if self.filters is not None:
for filter_ in self.filters(org_id=org_id):
conditions.append(filter_)
return Function("and", conditions)
@dataclass
| AliasedDerivedMetric |
python | tornadoweb__tornado | tornado/test/simple_httpclient_test.py | {
"start": 20671,
"end": 22686
} | class ____(AsyncHTTPSTestCase, SimpleHTTPClientTestMixin):
def setUp(self):
super().setUp()
self.http_client = self.create_client()
def get_app(self):
return self.mixin_get_app()
def create_client(self, **kwargs):
return SimpleAsyncHTTPClient(
force_instance=True, defaults=dict(validate_cert=False), **kwargs
)
def test_ssl_options(self):
resp = self.fetch("/hello", ssl_options={"cert_reqs": ssl.CERT_NONE})
self.assertEqual(resp.body, b"Hello world!")
def test_ssl_context(self):
ssl_ctx = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
ssl_ctx.check_hostname = False
ssl_ctx.verify_mode = ssl.CERT_NONE
resp = self.fetch("/hello", ssl_options=ssl_ctx)
self.assertEqual(resp.body, b"Hello world!")
def test_ssl_options_handshake_fail(self):
with ExpectLog(gen_log, "SSL Error|Uncaught exception", required=False):
with self.assertRaises(ssl.SSLError):
self.fetch(
"/hello",
ssl_options=dict(cert_reqs=ssl.CERT_REQUIRED),
raise_error=True,
)
def test_ssl_context_handshake_fail(self):
with ExpectLog(gen_log, "SSL Error|Uncaught exception"):
# CERT_REQUIRED is set by default.
ctx = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
with self.assertRaises(ssl.SSLError):
self.fetch("/hello", ssl_options=ctx, raise_error=True)
def test_error_logging(self):
# No stack traces are logged for SSL errors (in this case,
# failure to validate the testing self-signed cert).
# The SSLError is exposed through ssl.SSLError.
with ExpectLog(gen_log, ".*") as expect_log:
with self.assertRaises(ssl.SSLError):
self.fetch("/", validate_cert=True, raise_error=True)
self.assertFalse(expect_log.logged_stack)
| SimpleHTTPSClientTestCase |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/v1_compat_tests/scatter_nd_ops_test.py | {
"start": 2254,
"end": 5820
} | class ____(test.TestCase):
def _VariableRankTest(self,
np_scatter,
tf_scatter,
vtype,
itype,
repeat_indices=False):
np.random.seed(8)
ref_shapes = [(3, 6), (3, 6), (3, 6, 9), (3, 6, 9), (3, 6, 9), (3, 6, 9)]
indices_shapes = [(2,), (2, 2), (2,), (2, 2), (2, 3), (2, 3, 3)]
with test_util.device(use_gpu=True):
for ref_shape, indices_shape in zip(ref_shapes, indices_shapes):
num_updates = indices_shape[0]
ixdim = indices_shape[-1]
indexable_area_shape = ()
for i in range(ixdim):
indexable_area_shape += (ref_shape[i],)
all_indices = [
list(coord) for coord, _ in np.ndenumerate(
np.empty(indexable_area_shape, vtype))
]
np.random.shuffle(all_indices)
indices = np.array(all_indices[:num_updates])
if num_updates > 1 and repeat_indices:
indices = indices[:num_updates // 2]
for _ in range(num_updates - num_updates // 2):
indices = np.append(
indices, [indices[np.random.randint(num_updates // 2)]], axis=0)
np.random.shuffle(indices)
indices = _AsType(indices[:num_updates], itype)
updates_shape = (num_updates,)
for i in range(ixdim, len(ref_shape)):
updates_shape += (ref_shape[i],)
updates = _AsType(np.random.randn(*(updates_shape)), vtype)
ref = _AsType(np.random.randn(*(ref_shape)), vtype)
# Scatter via numpy
new = ref.copy()
np_scatter(new, indices, updates)
# Scatter via tensorflow
ref_var = variable_v1.VariableV1(ref)
self.evaluate(ref_var.initializer)
self.evaluate(tf_scatter(ref_var, indices, updates))
# Compare
self.assertAllClose(new, self.evaluate(ref_var))
def _ScatterRepeatIndicesTest(self, np_scatter, tf_scatter):
for vtype in (np.int32, np.float16, np.float32, np.float64):
for itype in (np.int32, np.int64):
self._VariableRankTest(
np_scatter, tf_scatter, vtype, itype, repeat_indices=True)
@test_util.run_v1_only("Don't need to test VariableV1 in TF2")
def testScatterRepeatIndicesMinMax(self):
"""This tests scatter_add using indices that repeat."""
self._ScatterRepeatIndicesTest(_NumpyMin, state_ops.scatter_nd_min)
self._ScatterRepeatIndicesTest(_NumpyMax, state_ops.scatter_nd_max)
@test_util.run_v1_only("Don't need to test VariableV1 in TF2")
def testScatterOutOfRangeCpu(self):
for op in (state_ops.scatter_nd_min, state_ops.scatter_nd_max):
params = np.array([1, 2, 3, 4, 5, 6]).astype(np.float32)
updates = np.array([-3, -4, -5]).astype(np.float32)
with self.cached_session(use_gpu=False):
ref = variable_v1.VariableV1(params)
self.evaluate(ref.initializer)
# Indices all in range, no problem.
indices = np.array([[2], [0], [5]])
self.evaluate(op(ref, indices, updates))
# Test some out of range errors.
indices = np.array([[-1], [0], [5]])
with self.assertRaisesOpError(
r"indices\[0\] = \[-1\] does not index into shape \[6\]"):
op(ref, indices, updates).eval()
indices = np.array([[2], [0], [6]])
with self.assertRaisesOpError(
r"indices\[2\] = \[6\] does not index into shape \[6\]"):
op(ref, indices, updates).eval()
if __name__ == "__main__":
test.main()
| StatefulScatterNdTest |
python | pypa__hatch | tests/backend/builders/plugin/test_interface.py | {
"start": 3702,
"end": 4863
} | class ____:
def test_unknown_version(self, isolation):
config = {
"project": {"name": "foo", "version": "0.1.0"},
"tool": {"hatch": {"build": {"targets": {"foo": {"versions": ["1"]}}}}},
}
builder = MockBuilder(str(isolation), config=config)
builder.PLUGIN_NAME = "foo"
builder.get_version_api = lambda: {"1": str}
with pytest.raises(ValueError, match="Unknown versions for target `foo`: 42, 9000"):
next(builder.build(directory=str(isolation), versions=["9000", "42"]))
def test_invalid_metadata(self, isolation):
config = {
"project": {"name": "foo", "version": "0.1.0", "dynamic": ["version"]},
"tool": {"hatch": {"build": {"targets": {"foo": {"versions": ["1"]}}}}},
}
builder = MockBuilder(str(isolation), config=config)
builder.PLUGIN_NAME = "foo"
with pytest.raises(
ValueError,
match="Metadata field `version` cannot be both statically defined and listed in field `project.dynamic`",
):
next(builder.build(directory=str(isolation)))
| TestBuildValidation |
python | pydata__xarray | xarray/tests/test_duck_array_ops.py | {
"start": 9738,
"end": 38155
} | class ____:
@pytest.mark.parametrize(
"arr1, arr2",
[
(np.array([1, 2, 3]), np.array([1, 2, 3])),
(np.array([1, 2, np.nan]), np.array([1, np.nan, 3])),
(np.array([np.nan, 2, np.nan]), np.array([1, np.nan, np.nan])),
],
)
def test_equal(self, arr1, arr2):
assert array_notnull_equiv(arr1, arr2)
def test_some_not_equal(self):
a = np.array([1, 2, 4])
b = np.array([1, np.nan, 3])
assert not array_notnull_equiv(a, b)
def test_wrong_shape(self):
a = np.array([[1, np.nan, np.nan, 4]])
b = np.array([[1, 2], [np.nan, 4]])
assert not array_notnull_equiv(a, b)
@pytest.mark.parametrize(
"val1, val2, val3, null",
[
(
np.datetime64("2000"),
np.datetime64("2001"),
np.datetime64("2002"),
np.datetime64("NaT"),
),
(1.0, 2.0, 3.0, np.nan),
("foo", "bar", "baz", None),
("foo", "bar", "baz", np.nan),
],
)
def test_types(self, val1, val2, val3, null):
dtype = object if isinstance(val1, str) else None
arr1 = np.array([val1, null, val3, null], dtype=dtype)
arr2 = np.array([val1, val2, null, null], dtype=dtype)
assert array_notnull_equiv(arr1, arr2)
def construct_dataarray(dim_num, dtype, contains_nan, dask):
# dimnum <= 3
rng = np.random.default_rng(0)
shapes = [16, 8, 4][:dim_num]
dims = ("x", "y", "z")[:dim_num]
if np.issubdtype(dtype, np.floating):
array = rng.random(shapes).astype(dtype)
elif np.issubdtype(dtype, np.integer):
array = rng.integers(0, 10, size=shapes).astype(dtype)
elif np.issubdtype(dtype, np.bool_):
array = rng.integers(0, 1, size=shapes).astype(dtype)
elif dtype is str:
array = rng.choice(["a", "b", "c", "d"], size=shapes)
else:
raise ValueError
if contains_nan:
inds = rng.choice(range(array.size), int(array.size * 0.2))
dtype, fill_value = dtypes.maybe_promote(array.dtype)
array = array.astype(dtype)
array.flat[inds] = fill_value
da = DataArray(array, dims=dims, coords={"x": np.arange(16)}, name="da")
if dask and has_dask:
chunks = dict.fromkeys(dims, 4)
da = da.chunk(chunks)
return da
def from_series_or_scalar(se):
if isinstance(se, pd.Series):
return DataArray.from_series(se)
else: # scalar case
return DataArray(se)
def series_reduce(da, func, dim, **kwargs):
"""convert DataArray to pd.Series, apply pd.func, then convert back to
a DataArray. Multiple dims cannot be specified."""
# pd no longer accepts skipna=None https://github.com/pandas-dev/pandas/issues/44178
if kwargs.get("skipna", True) is None:
kwargs["skipna"] = True
if dim is None or da.ndim == 1:
se = da.to_series()
return from_series_or_scalar(getattr(se, func)(**kwargs))
else:
dims = list(da.dims)
dims.remove(dim)
d = dims[0]
da1 = [
series_reduce(da.isel(**{d: i}), func, dim, **kwargs)
for i in range(len(da[d]))
]
if d in da.coords:
return concat(da1, dim=da[d])
return concat(da1, dim=d)
def assert_dask_array(da, dask):
if dask and da.ndim > 0:
assert isinstance(da.data, dask_array_type)
@arm_xfail
@pytest.mark.filterwarnings("ignore:All-NaN .* encountered:RuntimeWarning")
@pytest.mark.parametrize("dask", [False, True] if has_dask else [False])
def test_datetime_mean(dask: bool, time_unit: PDDatetimeUnitOptions) -> None:
# Note: only testing numpy, as dask is broken upstream
dtype = f"M8[{time_unit}]"
da = DataArray(
np.array(["2010-01-01", "NaT", "2010-01-03", "NaT", "NaT"], dtype=dtype),
dims=["time"],
)
if dask:
# Trigger use case where a chunk is full of NaT
da = da.chunk({"time": 3})
expect = DataArray(np.array("2010-01-02", dtype="M8[ns]"))
expect_nat = DataArray(np.array("NaT", dtype="M8[ns]"))
actual = da.mean()
if dask:
assert actual.chunks is not None
assert_equal(actual, expect)
actual = da.mean(skipna=False)
if dask:
assert actual.chunks is not None
assert_equal(actual, expect_nat)
# tests for 1d array full of NaT
assert_equal(da[[1]].mean(), expect_nat)
assert_equal(da[[1]].mean(skipna=False), expect_nat)
# tests for a 0d array
assert_equal(da[0].mean(), da[0])
assert_equal(da[0].mean(skipna=False), da[0])
assert_equal(da[1].mean(), expect_nat)
assert_equal(da[1].mean(skipna=False), expect_nat)
@requires_cftime
@pytest.mark.parametrize("dask", [False, True])
def test_cftime_datetime_mean(dask):
if dask and not has_dask:
pytest.skip("requires dask")
times = date_range("2000", periods=4, use_cftime=True)
da = DataArray(times, dims=["time"])
da_2d = DataArray(times.values.reshape(2, 2))
if dask:
da = da.chunk({"time": 2})
da_2d = da_2d.chunk({"dim_0": 2})
expected = da.isel(time=0)
# one compute needed to check the array contains cftime datetimes
with raise_if_dask_computes(max_computes=1):
result = da.isel(time=0).mean()
assert_dask_array(result, dask)
assert_equal(result, expected)
expected = DataArray(times.date_type(2000, 1, 2, 12))
with raise_if_dask_computes(max_computes=1):
result = da.mean()
assert_dask_array(result, dask)
assert_equal(result, expected)
with raise_if_dask_computes(max_computes=1):
result = da_2d.mean()
assert_dask_array(result, dask)
assert_equal(result, expected)
@pytest.mark.parametrize("dask", [False, True])
def test_mean_over_long_spanning_datetime64(dask) -> None:
if dask and not has_dask:
pytest.skip("requires dask")
array = np.array(["1678-01-01", "NaT", "2260-01-01"], dtype="datetime64[ns]")
da = DataArray(array, dims=["time"])
if dask:
da = da.chunk({"time": 2})
expected = DataArray(np.array("1969-01-01", dtype="datetime64[ns]"))
result = da.mean()
assert_equal(result, expected)
@requires_cftime
@requires_dask
def test_mean_over_non_time_dim_of_dataset_with_dask_backed_cftime_data():
# Regression test for part two of GH issue 5897: averaging over a non-time
# dimension still fails if the time variable is dask-backed.
ds = Dataset(
{
"var1": (
("time",),
date_range("2021-10-31", periods=10, freq="D", use_cftime=True),
),
"var2": (("x",), list(range(10))),
}
)
expected = ds.mean("x")
result = ds.chunk({}).mean("x")
assert_equal(result, expected)
@requires_cftime
def test_cftime_datetime_mean_long_time_period():
import cftime
times = np.array(
[
[
cftime.DatetimeNoLeap(400, 12, 31, 0, 0, 0, 0),
cftime.DatetimeNoLeap(520, 12, 31, 0, 0, 0, 0),
],
[
cftime.DatetimeNoLeap(520, 12, 31, 0, 0, 0, 0),
cftime.DatetimeNoLeap(640, 12, 31, 0, 0, 0, 0),
],
[
cftime.DatetimeNoLeap(640, 12, 31, 0, 0, 0, 0),
cftime.DatetimeNoLeap(760, 12, 31, 0, 0, 0, 0),
],
]
)
da = DataArray(times, dims=["time", "d2"])
result = da.mean("d2")
expected = DataArray(
[
cftime.DatetimeNoLeap(460, 12, 31, 0, 0, 0, 0),
cftime.DatetimeNoLeap(580, 12, 31, 0, 0, 0, 0),
cftime.DatetimeNoLeap(700, 12, 31, 0, 0, 0, 0),
],
dims=["time"],
)
assert_equal(result, expected)
def test_empty_axis_dtype():
ds = Dataset()
ds["pos"] = [1, 2, 3]
ds["data"] = ("pos", "time"), [[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]]
ds["var"] = "pos", [2, 3, 4]
assert_identical(ds.mean(dim="time")["var"], ds["var"])
assert_identical(ds.max(dim="time")["var"], ds["var"])
assert_identical(ds.min(dim="time")["var"], ds["var"])
assert_identical(ds.sum(dim="time")["var"], ds["var"])
@pytest.mark.parametrize("dim_num", [1, 2])
@pytest.mark.parametrize("dtype", [float, int, np.float32, np.bool_])
@pytest.mark.parametrize("dask", [False, True])
@pytest.mark.parametrize("func", ["sum", "min", "max", "mean", "var"])
# TODO test cumsum, cumprod
@pytest.mark.parametrize("skipna", [False, True])
@pytest.mark.parametrize("aggdim", [None, "x"])
def test_reduce(dim_num, dtype, dask, func, skipna, aggdim):
if aggdim == "y" and dim_num < 2:
pytest.skip("dim not in this test")
if dtype == np.bool_ and func == "mean":
pytest.skip("numpy does not support this")
if dask and not has_dask:
pytest.skip("requires dask")
if dask and skipna is False and dtype == np.bool_:
pytest.skip("dask does not compute object-typed array")
rtol = 1e-04 if dtype == np.float32 else 1e-05
da = construct_dataarray(dim_num, dtype, contains_nan=True, dask=dask)
axis = None if aggdim is None else da.get_axis_num(aggdim)
# TODO: remove these after resolving
# https://github.com/dask/dask/issues/3245
with warnings.catch_warnings():
warnings.filterwarnings("ignore", "Mean of empty slice")
warnings.filterwarnings("ignore", "All-NaN slice")
warnings.filterwarnings("ignore", "invalid value encountered in")
if da.dtype.kind == "O" and skipna:
# Numpy < 1.13 does not handle object-type array.
try:
if skipna:
expected = getattr(np, f"nan{func}")(da.values, axis=axis)
else:
expected = getattr(np, func)(da.values, axis=axis)
actual = getattr(da, func)(skipna=skipna, dim=aggdim)
assert_dask_array(actual, dask)
np.testing.assert_allclose(
actual.values, np.array(expected), rtol=1.0e-4, equal_nan=True
)
except (TypeError, AttributeError, ZeroDivisionError):
# TODO currently, numpy does not support some methods such as
# nanmean for object dtype
pass
actual = getattr(da, func)(skipna=skipna, dim=aggdim)
# for dask case, make sure the result is the same for numpy backend
expected = getattr(da.compute(), func)(skipna=skipna, dim=aggdim)
assert_allclose(actual, expected, rtol=rtol)
# make sure the compatibility with pandas' results.
if func in ["var", "std"]:
expected = series_reduce(da, func, skipna=skipna, dim=aggdim, ddof=0)
assert_allclose(actual, expected, rtol=rtol)
# also check ddof!=0 case
actual = getattr(da, func)(skipna=skipna, dim=aggdim, ddof=5)
if dask:
assert isinstance(da.data, dask_array_type)
expected = series_reduce(da, func, skipna=skipna, dim=aggdim, ddof=5)
assert_allclose(actual, expected, rtol=rtol)
else:
expected = series_reduce(da, func, skipna=skipna, dim=aggdim)
assert_allclose(actual, expected, rtol=rtol)
# make sure the dtype argument
if func not in ["max", "min"]:
actual = getattr(da, func)(skipna=skipna, dim=aggdim, dtype=float)
assert_dask_array(actual, dask)
assert actual.dtype == float
# without nan
da = construct_dataarray(dim_num, dtype, contains_nan=False, dask=dask)
actual = getattr(da, func)(skipna=skipna)
if dask:
assert isinstance(da.data, dask_array_type)
expected = getattr(np, f"nan{func}")(da.values)
if actual.dtype == object:
assert actual.values == np.array(expected)
else:
assert np.allclose(actual.values, np.array(expected), rtol=rtol)
@pytest.mark.parametrize("dim_num", [1, 2])
@pytest.mark.parametrize("dtype", [float, int, np.float32, np.bool_, str])
@pytest.mark.parametrize("contains_nan", [True, False])
@pytest.mark.parametrize("dask", [False, True])
@pytest.mark.parametrize("func", ["min", "max"])
@pytest.mark.parametrize("skipna", [False, True])
@pytest.mark.parametrize("aggdim", ["x", "y"])
def test_argmin_max(dim_num, dtype, contains_nan, dask, func, skipna, aggdim):
# pandas-dev/pandas#16830, we do not check consistency with pandas but
# just make sure da[da.argmin()] == da.min()
if aggdim == "y" and dim_num < 2:
pytest.skip("dim not in this test")
if dask and not has_dask:
pytest.skip("requires dask")
if contains_nan:
if not skipna:
pytest.skip("numpy's argmin (not nanargmin) does not handle object-dtype")
if skipna and np.dtype(dtype).kind in "iufc":
pytest.skip("numpy's nanargmin raises ValueError for all nan axis")
da = construct_dataarray(dim_num, dtype, contains_nan=contains_nan, dask=dask)
with warnings.catch_warnings():
warnings.filterwarnings("ignore", "All-NaN slice")
actual = da.isel(
**{aggdim: getattr(da, "arg" + func)(dim=aggdim, skipna=skipna).compute()}
)
expected = getattr(da, func)(dim=aggdim, skipna=skipna)
assert_allclose(
actual.drop_vars(list(actual.coords)),
expected.drop_vars(list(expected.coords)),
)
def test_argmin_max_error():
da = construct_dataarray(2, np.bool_, contains_nan=True, dask=False)
da[0] = np.nan
with pytest.raises(ValueError):
da.argmin(dim="y")
@pytest.mark.parametrize(
["array", "expected"],
[
(
np.array([np.datetime64("2000-01-01"), np.datetime64("NaT")]),
np.array([False, True]),
),
(
np.array([np.timedelta64(1, "h"), np.timedelta64("NaT")]),
np.array([False, True]),
),
(
np.array([0.0, np.nan]),
np.array([False, True]),
),
(
np.array([1j, np.nan]),
np.array([False, True]),
),
(
np.array(["foo", np.nan], dtype=object),
np.array([False, True]),
),
(
np.array([1, 2], dtype=int),
np.array([False, False]),
),
(
np.array([True, False], dtype=bool),
np.array([False, False]),
),
],
)
def test_isnull(array, expected):
actual = duck_array_ops.isnull(array)
np.testing.assert_equal(expected, actual)
@requires_dask
def test_isnull_with_dask():
da = construct_dataarray(2, np.float32, contains_nan=True, dask=True)
assert isinstance(da.isnull().data, dask_array_type)
assert_equal(da.isnull().load(), da.load().isnull())
@pytest.mark.skipif(not has_dask, reason="This is for dask.")
@pytest.mark.parametrize("axis", [0, -1, 1])
@pytest.mark.parametrize("edge_order", [1, 2])
def test_dask_gradient(axis, edge_order):
import dask.array as da
array = np.array(np.random.randn(100, 5, 40))
x = np.exp(np.linspace(0, 1, array.shape[axis]))
darray = da.from_array(array, chunks=[(6, 30, 30, 20, 14), 5, 8])
expected = gradient(array, x, axis=axis, edge_order=edge_order)
actual = gradient(darray, x, axis=axis, edge_order=edge_order)
assert isinstance(actual, da.Array)
assert_array_equal(actual, expected)
@pytest.mark.parametrize("dim_num", [1, 2])
@pytest.mark.parametrize("dtype", [float, int, np.float32, np.bool_])
@pytest.mark.parametrize("dask", [False, True])
@pytest.mark.parametrize("func", ["sum", "prod"])
@pytest.mark.parametrize("aggdim", [None, "x"])
@pytest.mark.parametrize("contains_nan", [True, False])
@pytest.mark.parametrize("skipna", [True, False, None])
def test_min_count(dim_num, dtype, dask, func, aggdim, contains_nan, skipna):
if dask and not has_dask:
pytest.skip("requires dask")
da = construct_dataarray(dim_num, dtype, contains_nan=contains_nan, dask=dask)
min_count = 3
# If using Dask, the function call should be lazy.
with raise_if_dask_computes():
actual = getattr(da, func)(dim=aggdim, skipna=skipna, min_count=min_count)
expected = series_reduce(da, func, skipna=skipna, dim=aggdim, min_count=min_count)
assert_allclose(actual, expected)
assert_dask_array(actual, dask)
@pytest.mark.parametrize("dtype", [float, int, np.float32, np.bool_])
@pytest.mark.parametrize("dask", [False, True])
@pytest.mark.parametrize("func", ["sum", "prod"])
def test_min_count_nd(dtype, dask, func):
if dask and not has_dask:
pytest.skip("requires dask")
min_count = 3
dim_num = 3
da = construct_dataarray(dim_num, dtype, contains_nan=True, dask=dask)
# If using Dask, the function call should be lazy.
with raise_if_dask_computes():
actual = getattr(da, func)(
dim=["x", "y", "z"], skipna=True, min_count=min_count
)
# Supplying all dims is equivalent to supplying `...` or `None`
expected = getattr(da, func)(dim=..., skipna=True, min_count=min_count)
assert_allclose(actual, expected)
assert_dask_array(actual, dask)
@pytest.mark.parametrize("dask", [False, True])
@pytest.mark.parametrize("func", ["sum", "prod"])
@pytest.mark.parametrize("dim", [None, "a", "b"])
def test_min_count_specific(dask, func, dim):
if dask and not has_dask:
pytest.skip("requires dask")
# Simple array with four non-NaN values.
da = DataArray(np.ones((6, 6), dtype=np.float64) * np.nan, dims=("a", "b"))
da[0][0] = 2
da[0][3] = 2
da[3][0] = 2
da[3][3] = 2
if dask:
da = da.chunk({"a": 3, "b": 3})
# Expected result if we set min_count to the number of non-NaNs in a
# row/column/the entire array.
if dim:
min_count = 2
expected = DataArray(
[4.0, np.nan, np.nan] * 2, dims=("a" if dim == "b" else "b",)
)
else:
min_count = 4
expected = DataArray(8.0 if func == "sum" else 16.0)
# Check for that min_count.
with raise_if_dask_computes():
actual = getattr(da, func)(dim, skipna=True, min_count=min_count)
assert_dask_array(actual, dask)
assert_allclose(actual, expected)
# With min_count being one higher, should get all NaN.
min_count += 1
expected *= np.nan
with raise_if_dask_computes():
actual = getattr(da, func)(dim, skipna=True, min_count=min_count)
assert_dask_array(actual, dask)
assert_allclose(actual, expected)
@pytest.mark.parametrize("func", ["sum", "prod"])
def test_min_count_dataset(func):
da = construct_dataarray(2, dtype=float, contains_nan=True, dask=False)
ds = Dataset({"var1": da}, coords={"scalar": 0})
actual = getattr(ds, func)(dim="x", skipna=True, min_count=3)["var1"]
expected = getattr(ds["var1"], func)(dim="x", skipna=True, min_count=3)
assert_allclose(actual, expected)
@pytest.mark.parametrize("dtype", [float, int, np.float32, np.bool_])
@pytest.mark.parametrize("dask", [False, True])
@pytest.mark.parametrize("skipna", [False, True])
@pytest.mark.parametrize("func", ["sum", "prod"])
def test_multiple_dims(dtype, dask, skipna, func):
if dask and not has_dask:
pytest.skip("requires dask")
da = construct_dataarray(3, dtype, contains_nan=True, dask=dask)
actual = getattr(da, func)(("x", "y"), skipna=skipna)
expected = getattr(getattr(da, func)("x", skipna=skipna), func)("y", skipna=skipna)
assert_allclose(actual, expected)
@pytest.mark.parametrize("dask", [True, False])
def test_datetime_to_numeric_datetime64(dask, time_unit: PDDatetimeUnitOptions):
if dask and not has_dask:
pytest.skip("requires dask")
times = pd.date_range("2000", periods=5, freq="7D").as_unit(time_unit).values
if dask:
import dask.array
times = dask.array.from_array(times, chunks=-1)
with raise_if_dask_computes():
result = duck_array_ops.datetime_to_numeric(times, datetime_unit="h")
expected = 24 * np.arange(0, 35, 7)
np.testing.assert_array_equal(result, expected)
offset = times[1]
with raise_if_dask_computes():
result = duck_array_ops.datetime_to_numeric(
times, offset=offset, datetime_unit="h"
)
expected = 24 * np.arange(-7, 28, 7)
np.testing.assert_array_equal(result, expected)
dtype = np.float32
with raise_if_dask_computes():
result = duck_array_ops.datetime_to_numeric(
times, datetime_unit="h", dtype=dtype
)
expected2 = 24 * np.arange(0, 35, 7).astype(dtype)
np.testing.assert_array_equal(result, expected2)
@requires_cftime
@pytest.mark.parametrize("dask", [True, False])
def test_datetime_to_numeric_cftime(dask):
if dask and not has_dask:
pytest.skip("requires dask")
times = date_range(
"2000", periods=5, freq="7D", calendar="standard", use_cftime=True
).values
if dask:
import dask.array
times = dask.array.from_array(times, chunks=-1)
with raise_if_dask_computes():
result = duck_array_ops.datetime_to_numeric(times, datetime_unit="h", dtype=int)
expected = 24 * np.arange(0, 35, 7)
np.testing.assert_array_equal(result, expected)
offset = times[1]
with raise_if_dask_computes():
result = duck_array_ops.datetime_to_numeric(
times, offset=offset, datetime_unit="h", dtype=int
)
expected = 24 * np.arange(-7, 28, 7)
np.testing.assert_array_equal(result, expected)
dtype = np.float32
with raise_if_dask_computes():
result = duck_array_ops.datetime_to_numeric(
times, datetime_unit="h", dtype=dtype
)
expected2: Any = 24 * np.arange(0, 35, 7).astype(dtype)
np.testing.assert_array_equal(result, expected2)
with raise_if_dask_computes():
if dask:
time = dask.array.asarray(times[1])
else:
time = np.asarray(times[1])
result = duck_array_ops.datetime_to_numeric(
time, offset=times[0], datetime_unit="h", dtype=int
)
expected3 = np.array(24 * 7).astype(int)
np.testing.assert_array_equal(result, expected3)
@requires_cftime
def test_datetime_to_numeric_potential_overflow(time_unit: PDDatetimeUnitOptions):
import cftime
if time_unit == "ns":
pytest.skip("out-of-bounds datetime64 overflow")
dtype = f"M8[{time_unit}]"
times = pd.date_range("2000", periods=5, freq="7D").values.astype(dtype)
cftimes = date_range(
"2000", periods=5, freq="7D", calendar="proleptic_gregorian", use_cftime=True
).values
offset = np.datetime64("0001-01-01", time_unit)
cfoffset = cftime.DatetimeProlepticGregorian(1, 1, 1)
result = duck_array_ops.datetime_to_numeric(
times, offset=offset, datetime_unit="D", dtype=int
)
cfresult = duck_array_ops.datetime_to_numeric(
cftimes, offset=cfoffset, datetime_unit="D", dtype=int
)
expected = 730119 + np.arange(0, 35, 7)
np.testing.assert_array_equal(result, expected)
np.testing.assert_array_equal(cfresult, expected)
def test_py_timedelta_to_float():
assert py_timedelta_to_float(dt.timedelta(days=1), "ns") == 86400 * 1e9
assert py_timedelta_to_float(dt.timedelta(days=1e6), "ps") == 86400 * 1e18
assert py_timedelta_to_float(dt.timedelta(days=1e6), "ns") == 86400 * 1e15
assert py_timedelta_to_float(dt.timedelta(days=1e6), "us") == 86400 * 1e12
assert py_timedelta_to_float(dt.timedelta(days=1e6), "ms") == 86400 * 1e9
assert py_timedelta_to_float(dt.timedelta(days=1e6), "s") == 86400 * 1e6
assert py_timedelta_to_float(dt.timedelta(days=1e6), "D") == 1e6
@pytest.mark.parametrize("np_dt_unit", ["D", "h", "m", "s", "ms", "us", "ns"])
def test_np_timedelta64_to_float(
np_dt_unit: NPDatetimeUnitOptions, time_unit: PDDatetimeUnitOptions
):
# tests any combination of source np.timedelta64 (NPDatetimeUnitOptions) with
# np_timedelta_to_float with dedicated target unit (PDDatetimeUnitOptions)
td = np.timedelta64(1, np_dt_unit)
expected = _NS_PER_TIME_DELTA[np_dt_unit] / _NS_PER_TIME_DELTA[time_unit]
out = np_timedelta64_to_float(td, datetime_unit=time_unit)
np.testing.assert_allclose(out, expected)
assert isinstance(out, float)
out = np_timedelta64_to_float(np.atleast_1d(td), datetime_unit=time_unit)
np.testing.assert_allclose(out, expected)
@pytest.mark.parametrize("np_dt_unit", ["D", "h", "m", "s", "ms", "us", "ns"])
def test_pd_timedelta_to_float(
np_dt_unit: NPDatetimeUnitOptions, time_unit: PDDatetimeUnitOptions
):
# tests any combination of source pd.Timedelta (NPDatetimeUnitOptions) with
# np_timedelta_to_float with dedicated target unit (PDDatetimeUnitOptions)
td = pd.Timedelta(1, np_dt_unit)
expected = _NS_PER_TIME_DELTA[np_dt_unit] / _NS_PER_TIME_DELTA[time_unit]
out = pd_timedelta_to_float(td, datetime_unit=time_unit)
np.testing.assert_allclose(out, expected)
assert isinstance(out, float)
@pytest.mark.parametrize(
"td", [dt.timedelta(days=1), np.timedelta64(1, "D"), pd.Timedelta(1, "D"), "1 day"]
)
def test_timedelta_to_numeric(td, time_unit: PDDatetimeUnitOptions):
# Scalar input
out = timedelta_to_numeric(td, time_unit)
expected = _NS_PER_TIME_DELTA["D"] / _NS_PER_TIME_DELTA[time_unit]
np.testing.assert_allclose(out, expected)
assert isinstance(out, float)
@pytest.mark.parametrize("use_dask", [True, False])
@pytest.mark.parametrize("skipna", [True, False])
def test_least_squares(use_dask, skipna):
if use_dask and (not has_dask or not has_scipy):
pytest.skip("requires dask and scipy")
lhs = np.array([[1, 2], [1, 2], [3, 2]])
rhs = DataArray(np.array([3, 5, 7]), dims=("y",))
if use_dask:
rhs = rhs.chunk({"y": 1})
coeffs, residuals = least_squares(lhs, rhs.data, skipna=skipna)
np.testing.assert_allclose(coeffs, [1.5, 1.25])
np.testing.assert_allclose(residuals, [2.0])
@requires_dask
@requires_bottleneck
@pytest.mark.parametrize("method", ["sequential", "blelloch"])
@pytest.mark.parametrize(
"arr",
[
[np.nan, 1, 2, 3, np.nan, np.nan, np.nan, np.nan, 4, 5, np.nan, 6],
[
np.nan,
np.nan,
np.nan,
2,
np.nan,
np.nan,
np.nan,
9,
np.nan,
np.nan,
np.nan,
np.nan,
],
],
)
def test_push_dask(method, arr):
import bottleneck
import dask.array as da
arr = np.array(arr)
chunks = list(range(1, 11)) + [(1, 2, 3, 2, 2, 1, 1)]
for n in [None, 1, 2, 3, 4, 5, 11]:
expected = bottleneck.push(arr, axis=0, n=n)
for c in chunks:
with raise_if_dask_computes():
actual = push(da.from_array(arr, chunks=c), axis=0, n=n, method=method)
np.testing.assert_equal(actual, expected)
def test_extension_array_equality(categorical1, int1):
int_duck_array = PandasExtensionArray(int1)
categorical_duck_array = PandasExtensionArray(categorical1)
assert (int_duck_array != categorical_duck_array).all()
assert (categorical_duck_array == categorical1).all()
assert (int_duck_array[0:2] == int1[0:2]).all()
def test_extension_array_singleton_equality(categorical1):
categorical_duck_array = PandasExtensionArray(categorical1)
assert (categorical_duck_array != "cat3").all()
def test_extension_array_repr(int1):
int_duck_array = PandasExtensionArray(int1)
assert repr(int1) in repr(int_duck_array)
def test_extension_array_attr():
array = pd.Categorical(["cat2", "cat1", "cat2", "cat3", "cat1"])
wrapped = PandasExtensionArray(array)
assert_array_equal(array.categories, wrapped.categories)
assert array.nbytes == wrapped.nbytes
roundtripped = pickle.loads(pickle.dumps(wrapped))
assert isinstance(roundtripped, PandasExtensionArray)
assert (roundtripped == wrapped).all()
interval_array = pd.arrays.IntervalArray.from_breaks([0, 1, 2, 3], closed="right")
wrapped = PandasExtensionArray(interval_array)
assert_array_equal(wrapped.left, interval_array.left, strict=True)
assert wrapped.closed == interval_array.closed
| TestArrayNotNullEquiv |
python | pandas-dev__pandas | pandas/tests/window/test_online.py | {
"start": 603,
"end": 3644
} | class ____:
def test_invalid_update(self):
df = DataFrame({"a": range(5), "b": range(5)})
online_ewm = df.head(2).ewm(0.5).online()
with pytest.raises(
ValueError,
match="Must call mean with update=None first before passing update",
):
online_ewm.mean(update=df.head(1))
@pytest.mark.slow
@pytest.mark.parametrize(
"obj", [DataFrame({"a": range(5), "b": range(5)}), Series(range(5), name="foo")]
)
def test_online_vs_non_online_mean(
self, obj, nogil, parallel, nopython, adjust, ignore_na
):
expected = obj.ewm(0.5, adjust=adjust, ignore_na=ignore_na).mean()
engine_kwargs = {"nogil": nogil, "parallel": parallel, "nopython": nopython}
online_ewm = (
obj.head(2)
.ewm(0.5, adjust=adjust, ignore_na=ignore_na)
.online(engine_kwargs=engine_kwargs)
)
# Test resetting once
for _ in range(2):
result = online_ewm.mean()
tm.assert_equal(result, expected.head(2))
result = online_ewm.mean(update=obj.tail(3))
tm.assert_equal(result, expected.tail(3))
online_ewm.reset()
@pytest.mark.xfail(raises=NotImplementedError)
@pytest.mark.parametrize(
"obj", [DataFrame({"a": range(5), "b": range(5)}), Series(range(5), name="foo")]
)
def test_update_times_mean(
self, obj, nogil, parallel, nopython, adjust, ignore_na, halflife_with_times
):
times = Series(
np.array(
["2020-01-01", "2020-01-05", "2020-01-07", "2020-01-17", "2020-01-21"],
dtype="datetime64[ns]",
)
)
expected = obj.ewm(
0.5,
adjust=adjust,
ignore_na=ignore_na,
times=times,
halflife=halflife_with_times,
).mean()
engine_kwargs = {"nogil": nogil, "parallel": parallel, "nopython": nopython}
online_ewm = (
obj.head(2)
.ewm(
0.5,
adjust=adjust,
ignore_na=ignore_na,
times=times.head(2),
halflife=halflife_with_times,
)
.online(engine_kwargs=engine_kwargs)
)
# Test resetting once
for _ in range(2):
result = online_ewm.mean()
tm.assert_equal(result, expected.head(2))
result = online_ewm.mean(update=obj.tail(3), update_times=times.tail(3))
tm.assert_equal(result, expected.tail(3))
online_ewm.reset()
@pytest.mark.parametrize("method", ["aggregate", "std", "corr", "cov", "var"])
def test_ewm_notimplementederror_raises(self, method):
ser = Series(range(10))
kwargs = {}
if method == "aggregate":
kwargs["func"] = lambda x: x
with pytest.raises(NotImplementedError, match=".* is not implemented."):
getattr(ser.ewm(1).online(), method)(**kwargs)
| TestEWM |
python | xlwings__xlwings | xlwings/constants.py | {
"start": 86276,
"end": 86404
} | class ____:
xlPrinter = 2 # from enum XlPictureAppearance
xlScreen = 1 # from enum XlPictureAppearance
| PictureAppearance |
python | networkx__networkx | networkx/algorithms/tests/test_summarization.py | {
"start": 7970,
"end": 9006
} | class ____:
node_attributes = ("color",)
def build_original_graph(self):
pass
def build_summary_graph(self):
pass
def test_summary_graph(self):
original_graph = self.build_original_graph()
summary_graph = self.build_summary_graph()
relationship_attributes = ("type",)
generated_summary_graph = nx.snap_aggregation(
original_graph, self.node_attributes, relationship_attributes
)
relabeled_summary_graph = self.deterministic_labels(generated_summary_graph)
assert nx.is_isomorphic(summary_graph, relabeled_summary_graph)
def deterministic_labels(self, G):
node_labels = list(G.nodes)
node_labels = sorted(node_labels, key=lambda n: sorted(G.nodes[n]["group"])[0])
node_labels.sort()
label_mapping = {}
for index, node in enumerate(node_labels):
label = f"Supernode-{index}"
label_mapping[node] = label
return nx.relabel_nodes(G, label_mapping)
| AbstractSNAP |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_alloy_db.py | {
"start": 88047,
"end": 92283
} | class ____:
def setup_method(self):
self.operator = AlloyDBDeleteBackupOperator(
task_id=TEST_TASK_ID,
backup_id=TEST_BACKUP_ID,
project_id=TEST_GCP_PROJECT,
location=TEST_GCP_REGION,
gcp_conn_id=TEST_GCP_CONN_ID,
request_id=TEST_REQUEST_ID,
validate_request=TEST_VALIDATE_ONLY,
retry=TEST_RETRY,
timeout=TEST_TIMEOUT,
metadata=TEST_METADATA,
impersonation_chain=TEST_IMPERSONATION_CHAIN,
)
def test_init(self):
assert self.operator.backup_id == TEST_BACKUP_ID
def test_template_fields(self):
expected_template_fields = {"backup_id"} | set(AlloyDBWriteBaseOperator.template_fields)
assert set(AlloyDBDeleteBackupOperator.template_fields) == expected_template_fields
@mock.patch(DELETE_BACKUP_OPERATOR_PATH.format("get_operation_result"))
@mock.patch(DELETE_BACKUP_OPERATOR_PATH.format("log"))
@mock.patch(ALLOY_DB_HOOK_PATH, new_callable=mock.PropertyMock)
def test_execute(self, mock_hook, mock_log, mock_get_operation_result):
mock_delete_backup = mock_hook.return_value.delete_backup
mock_operation = mock_delete_backup.return_value
mock_context = mock.MagicMock()
result = self.operator.execute(context=mock_context)
mock_delete_backup.assert_called_once_with(
backup_id=TEST_BACKUP_ID,
project_id=TEST_GCP_PROJECT,
location=TEST_GCP_REGION,
request_id=TEST_REQUEST_ID,
validate_only=TEST_VALIDATE_ONLY,
retry=TEST_RETRY,
timeout=TEST_TIMEOUT,
metadata=TEST_METADATA,
)
mock_get_operation_result.assert_called_once_with(mock_operation)
assert result is None
mock_log.info.assert_has_calls(
[
call("Deleting an AlloyDB backup."),
call("AlloyDB backup %s was successfully removed.", TEST_BACKUP_ID),
]
)
@mock.patch(DELETE_BACKUP_OPERATOR_PATH.format("get_operation_result"))
@mock.patch(DELETE_BACKUP_OPERATOR_PATH.format("log"))
@mock.patch(ALLOY_DB_HOOK_PATH, new_callable=mock.PropertyMock)
def test_execute_validate_request(self, mock_hook, mock_log, mock_get_operation_result):
mock_delete_backup = mock_hook.return_value.delete_backup
mock_operation = mock_delete_backup.return_value
mock_context = mock.MagicMock()
self.operator.validate_request = True
result = self.operator.execute(context=mock_context)
mock_delete_backup.assert_called_once_with(
backup_id=TEST_BACKUP_ID,
project_id=TEST_GCP_PROJECT,
location=TEST_GCP_REGION,
request_id=TEST_REQUEST_ID,
validate_only=True,
retry=TEST_RETRY,
timeout=TEST_TIMEOUT,
metadata=TEST_METADATA,
)
mock_get_operation_result.assert_called_once_with(mock_operation)
assert result is None
mock_log.info.assert_called_once_with("Validating a Delete AlloyDB backup request.")
@mock.patch(DELETE_BACKUP_OPERATOR_PATH.format("get_operation_result"))
@mock.patch(DELETE_BACKUP_OPERATOR_PATH.format("log"))
@mock.patch(ALLOY_DB_HOOK_PATH, new_callable=mock.PropertyMock)
def test_execute_exception(self, mock_hook, mock_log, mock_get_operation_result):
mock_delete_backup = mock_hook.return_value.delete_backup
mock_delete_backup.side_effect = Exception
mock_context = mock.MagicMock()
with pytest.raises(AirflowException):
_ = self.operator.execute(context=mock_context)
mock_delete_backup.assert_called_once_with(
backup_id=TEST_BACKUP_ID,
project_id=TEST_GCP_PROJECT,
location=TEST_GCP_REGION,
request_id=TEST_REQUEST_ID,
validate_only=TEST_VALIDATE_ONLY,
retry=TEST_RETRY,
timeout=TEST_TIMEOUT,
metadata=TEST_METADATA,
)
assert not mock_get_operation_result.called
mock_log.info.assert_called_once_with("Deleting an AlloyDB backup.")
| TestAlloyDBDeleteBackupOperator |
python | Netflix__metaflow | metaflow/plugins/aws/step_functions/step_functions.py | {
"start": 962,
"end": 47506
} | class ____(object):
def __init__(
self,
name,
graph,
flow,
code_package_metadata,
code_package_sha,
code_package_url,
production_token,
metadata,
flow_datastore,
environment,
event_logger,
monitor,
tags=None,
aws_batch_tags=None,
namespace=None,
username=None,
max_workers=None,
workflow_timeout=None,
is_project=False,
use_distributed_map=False,
compress_state_machine=False,
):
self.name = name
self.graph = graph
self.flow = flow
self.code_package_metadata = code_package_metadata
self.code_package_sha = code_package_sha
self.code_package_url = code_package_url
self.production_token = production_token
self.metadata = metadata
self.flow_datastore = flow_datastore
self.environment = environment
self.event_logger = event_logger
self.monitor = monitor
self.tags = tags
self.aws_batch_tags = aws_batch_tags or {}
self.namespace = namespace
self.username = username
self.max_workers = max_workers
self.workflow_timeout = workflow_timeout
self.config_parameters = self._process_config_parameters()
# https://aws.amazon.com/blogs/aws/step-functions-distributed-map-a-serverless-solution-for-large-scale-parallel-data-processing/
self.use_distributed_map = use_distributed_map
# S3 command upload configuration
self.compress_state_machine = compress_state_machine
self._client = StepFunctionsClient()
self._workflow = self._compile()
self._cron = self._cron()
self._state_machine_arn = None
def to_json(self):
return self._workflow.to_json(pretty=True)
def trigger_explanation(self):
if self._cron:
# Sometime in the future, we should vendor (or write) a utility
# that can translate cron specifications into a human-readable
# format and push to the user for a better UX, someday.
return (
"This workflow triggers automatically "
"via a cron schedule *%s* defined in AWS EventBridge."
% self.event_bridge_rule
)
else:
return "No triggers defined. " "You need to launch this workflow manually."
def deploy(self, log_execution_history):
if SFN_IAM_ROLE is None:
raise StepFunctionsException(
"No IAM role found for AWS Step "
"Functions. You can create one "
"following the instructions listed at "
"*https://admin-docs.metaflow.org/meta"
"flow-on-aws/deployment-guide/manual-d"
"eployment#scheduling* and "
"re-configure Metaflow using "
"*metaflow configure aws* on your "
"terminal."
)
if log_execution_history:
if SFN_EXECUTION_LOG_GROUP_ARN is None:
raise StepFunctionsException(
"No AWS CloudWatch Logs log "
"group ARN found for emitting "
"state machine execution logs for "
"your workflow. You can set it in "
"your environment by using the "
"METAFLOW_SFN_EXECUTION_LOG_GROUP_ARN "
"environment variable."
)
try:
self._state_machine_arn = self._client.push(
name=self.name,
definition=self.to_json(),
role_arn=SFN_IAM_ROLE,
log_execution_history=log_execution_history,
)
except Exception as e:
raise StepFunctionsException(repr(e))
def schedule(self):
# Scheduling is currently enabled via AWS Event Bridge.
if EVENTS_SFN_ACCESS_IAM_ROLE is None:
raise StepFunctionsSchedulingException(
"No IAM role found for AWS "
"Events Bridge. You can "
"create one following the "
"instructions listed at "
"*https://admin-docs.metaflo"
"w.org/metaflow-on-aws/deplo"
"yment-guide/manual-deployme"
"nt#scheduling* and "
"re-configure Metaflow "
"using *metaflow configure "
"aws* on your terminal."
)
try:
self.event_bridge_rule = (
EventBridgeClient(self.name)
.cron(self._cron)
.role_arn(EVENTS_SFN_ACCESS_IAM_ROLE)
.state_machine_arn(self._state_machine_arn)
.schedule()
)
except Exception as e:
raise StepFunctionsSchedulingException(repr(e))
@classmethod
def delete(cls, name):
# Always attempt to delete the event bridge rule.
schedule_deleted = EventBridgeClient(name).delete()
sfn_deleted = StepFunctionsClient().delete(name)
if sfn_deleted is None:
raise StepFunctionsException(
"The workflow *%s* doesn't exist on AWS Step Functions." % name
)
return schedule_deleted, sfn_deleted
@classmethod
def terminate(cls, flow_name, name):
client = StepFunctionsClient()
execution_arn, _, _, _ = cls.get_execution(flow_name, name)
response = client.terminate_execution(execution_arn)
return response
@classmethod
def trigger(cls, name, parameters):
try:
state_machine = StepFunctionsClient().get(name)
except Exception as e:
raise StepFunctionsException(repr(e))
if state_machine is None:
raise StepFunctionsException(
"The workflow *%s* doesn't exist "
"on AWS Step Functions. Please "
"deploy your flow first." % name
)
# Dump parameters into `Parameters` input field.
input = json.dumps({"Parameters": json.dumps(parameters)})
# AWS Step Functions limits input to be 32KiB, but AWS Batch
# has its own limitation of 30KiB for job specification length.
# Reserving 10KiB for rest of the job specification leaves 20KiB
# for us, which should be enough for most use cases for now.
if len(input) > 20480:
raise StepFunctionsException(
"Length of parameter names and "
"values shouldn't exceed 20480 as "
"imposed by AWS Step Functions."
)
try:
state_machine_arn = state_machine.get("stateMachineArn")
return StepFunctionsClient().trigger(state_machine_arn, input)
except Exception as e:
raise StepFunctionsException(repr(e))
@classmethod
def list(cls, name, states):
try:
state_machine = StepFunctionsClient().get(name)
except Exception as e:
raise StepFunctionsException(repr(e))
if state_machine is None:
raise StepFunctionsException(
"The workflow *%s* doesn't exist " "on AWS Step Functions." % name
)
try:
state_machine_arn = state_machine.get("stateMachineArn")
return StepFunctionsClient().list_executions(state_machine_arn, states)
except Exception as e:
raise StepFunctionsException(repr(e))
@classmethod
def get_existing_deployment(cls, name):
workflow = StepFunctionsClient().get(name)
if workflow is not None:
try:
start = json.loads(workflow["definition"])["States"]["start"]
parameters = start["Parameters"]["Parameters"]
return parameters.get("metaflow.owner"), parameters.get(
"metaflow.production_token"
)
except KeyError:
raise StepFunctionsException(
"An existing non-metaflow "
"workflow with the same name as "
"*%s* already exists in AWS Step "
"Functions. Please modify the "
"name of this flow or delete your "
"existing workflow on AWS Step "
"Functions." % name
)
return None
@classmethod
def get_execution(cls, state_machine_name, name):
client = StepFunctionsClient()
try:
state_machine = client.get(state_machine_name)
except Exception as e:
raise StepFunctionsException(repr(e))
if state_machine is None:
raise StepFunctionsException(
"The state machine *%s* doesn't exist on AWS Step Functions."
% state_machine_name
)
try:
state_machine_arn = state_machine.get("stateMachineArn")
environment_vars = (
json.loads(state_machine.get("definition"))
.get("States")
.get("start")
.get("Parameters")
.get("ContainerOverrides")
.get("Environment")
)
parameters = {
item.get("Name"): item.get("Value") for item in environment_vars
}
executions = client.list_executions(state_machine_arn, states=["RUNNING"])
for execution in executions:
if execution.get("name") == name:
try:
return (
execution.get("executionArn"),
parameters.get("METAFLOW_OWNER"),
parameters.get("METAFLOW_PRODUCTION_TOKEN"),
parameters.get("SFN_STATE_MACHINE"),
)
except KeyError:
raise StepFunctionsException(
"A non-metaflow workflow *%s* already exists in AWS Step Functions."
% name
)
return None
except Exception as e:
raise StepFunctionsException(repr(e))
def _compile(self):
if self.flow._flow_decorators.get("trigger") or self.flow._flow_decorators.get(
"trigger_on_finish"
):
raise StepFunctionsException(
"Deploying flows with @trigger or @trigger_on_finish decorator(s) "
"to AWS Step Functions is not supported currently."
)
if self.flow._flow_decorators.get("exit_hook"):
raise StepFunctionsException(
"Deploying flows with the @exit_hook decorator "
"to AWS Step Functions is not currently supported."
)
# Visit every node of the flow and recursively build the state machine.
def _visit(node, workflow, exit_node=None):
if node.parallel_foreach:
raise StepFunctionsException(
"Deploying flows with @parallel decorator(s) "
"to AWS Step Functions is not supported currently."
)
if node.type == "split-switch":
raise StepFunctionsException(
"Deploying flows with switch statement "
"to AWS Step Functions is not supported currently."
)
# Assign an AWS Batch job to the AWS Step Functions state
# and pass the intermediate state by exposing `JobId` and
# `Parameters` to the child job(s) as outputs. `Index` and
# `SplitParentTaskId` are populated optionally, when available.
# We can't modify the names of keys in AWS Step Functions aside
# from a blessed few which are set as `Parameters` for the Map
# state. That's why even though `JobId` refers to the parent task
# id, we can't call it as such. Similar situation for `Parameters`.
state = (
State(node.name)
.batch(self._batch(node))
.output_path(
"$.['JobId', " "'Parameters', " "'Index', " "'SplitParentTaskId']"
)
)
# End the (sub)workflow if we have reached the end of the flow or
# the parent step of matching_join of the sub workflow.
if node.type == "end" or exit_node in node.out_funcs:
workflow.add_state(state.end())
# Continue linear assignment within the (sub)workflow if the node
# doesn't branch or fork.
elif node.type in ("start", "linear", "join"):
workflow.add_state(state.next(node.out_funcs[0]))
_visit(self.graph[node.out_funcs[0]], workflow, exit_node)
# Create a `Parallel` state and assign sub workflows if the node
# branches out.
elif node.type == "split":
branch_name = hashlib.sha224(
"&".join(node.out_funcs).encode("utf-8")
).hexdigest()
workflow.add_state(state.next(branch_name))
branch = Parallel(branch_name).next(node.matching_join)
# Generate as many sub workflows as branches and recurse.
for n in node.out_funcs:
branch.branch(
_visit(
self.graph[n], Workflow(n).start_at(n), node.matching_join
)
)
workflow.add_state(branch)
# Continue the traversal from the matching_join.
_visit(self.graph[node.matching_join], workflow, exit_node)
# Create a `Map` state and assign sub workflow if the node forks.
elif node.type == "foreach":
# Fetch runtime cardinality via an AWS DynamoDb Get call before
# configuring the node
cardinality_state_name = "#%s" % node.out_funcs[0]
workflow.add_state(state.next(cardinality_state_name))
cardinality_state = (
State(cardinality_state_name)
.dynamo_db(SFN_DYNAMO_DB_TABLE, "$.JobId", "for_each_cardinality")
.result_path("$.Result")
)
iterator_name = "*%s" % node.out_funcs[0]
workflow.add_state(cardinality_state.next(iterator_name))
workflow.add_state(
Map(iterator_name)
.items_path("$.Result.Item.for_each_cardinality.NS")
.parameter("JobId.$", "$.JobId")
.parameter("SplitParentTaskId.$", "$.JobId")
.parameter("Parameters.$", "$.Parameters")
.parameter("Index.$", "$$.Map.Item.Value")
.next(
"%s_*GetManifest" % iterator_name
if self.use_distributed_map
else node.matching_join
)
.iterator(
_visit(
self.graph[node.out_funcs[0]],
Workflow(node.out_funcs[0])
.start_at(node.out_funcs[0])
.mode(
"DISTRIBUTED" if self.use_distributed_map else "INLINE"
),
node.matching_join,
)
)
.max_concurrency(self.max_workers)
# AWS Step Functions has a short coming for DistributedMap at the
# moment that does not allow us to subset the output of for-each
# to just a single element. We have to rely on a rather terrible
# hack and resort to using ResultWriter to write the state to
# Amazon S3 and process it in another task. But, well what can we
# do...
.result_writer(
*(
(
(
SFN_S3_DISTRIBUTED_MAP_OUTPUT_PATH[len("s3://") :]
if SFN_S3_DISTRIBUTED_MAP_OUTPUT_PATH.startswith(
"s3://"
)
else SFN_S3_DISTRIBUTED_MAP_OUTPUT_PATH
).split("/", 1)
+ [""]
)[:2]
if self.use_distributed_map
else (None, None)
)
)
.output_path("$" if self.use_distributed_map else "$.[0]")
)
if self.use_distributed_map:
workflow.add_state(
State("%s_*GetManifest" % iterator_name)
.resource("arn:aws:states:::aws-sdk:s3:getObject")
.parameter("Bucket.$", "$.ResultWriterDetails.Bucket")
.parameter("Key.$", "$.ResultWriterDetails.Key")
.next("%s_*Map" % iterator_name)
.result_selector("Body.$", "States.StringToJson($.Body)")
)
workflow.add_state(
Map("%s_*Map" % iterator_name)
.iterator(
Workflow("%s_*PassWorkflow" % iterator_name)
.mode("DISTRIBUTED")
.start_at("%s_*Pass" % iterator_name)
.add_state(
Pass("%s_*Pass" % iterator_name)
.end()
.parameter("Output.$", "States.StringToJson($.Output)")
.output_path("$.Output")
)
)
.next(node.matching_join)
.max_concurrency(1000)
.item_reader(
JSONItemReader()
.resource("arn:aws:states:::s3:getObject")
.parameter("Bucket.$", "$.Body.DestinationBucket")
.parameter("Key.$", "$.Body.ResultFiles.SUCCEEDED[0].Key")
)
.output_path("$.[0]")
)
# Continue the traversal from the matching_join.
_visit(self.graph[node.matching_join], workflow, exit_node)
# We shouldn't ideally ever get here.
else:
raise StepFunctionsException(
"Node type *%s* for step *%s* "
"is not currently supported by "
"AWS Step Functions." % (node.type, node.name)
)
return workflow
workflow = Workflow(self.name).start_at("start")
if self.workflow_timeout:
workflow.timeout_seconds(self.workflow_timeout)
return _visit(self.graph["start"], workflow)
def _cron(self):
schedule = self.flow._flow_decorators.get("schedule")
if schedule:
schedule = schedule[0]
if schedule.timezone is not None:
raise StepFunctionsException(
"Step Functions does not support scheduling with a timezone."
)
return schedule.schedule
return None
def _process_parameters(self):
parameters = []
has_schedule = self._cron() is not None
seen = set()
for var, param in self.flow._get_parameters():
# Throw an exception if the parameter is specified twice.
norm = param.name.lower()
if norm in seen:
raise MetaflowException(
"Parameter *%s* is specified twice. "
"Note that parameter names are "
"case-insensitive." % param.name
)
seen.add(norm)
# NOTE: We skip config parameters as these do not have dynamic values,
# and need to be treated differently.
if param.IS_CONFIG_PARAMETER:
continue
is_required = param.kwargs.get("required", False)
# Throw an exception if a schedule is set for a flow with required
# parameters with no defaults. We currently don't have any notion
# of data triggers in AWS Event Bridge.
if "default" not in param.kwargs and is_required and has_schedule:
raise MetaflowException(
"The parameter *%s* does not have a "
"default and is required. Scheduling "
"such parameters via AWS Event Bridge "
"is not currently supported." % param.name
)
value = deploy_time_eval(param.kwargs.get("default"))
parameters.append(dict(name=param.name, value=value))
return parameters
def _process_config_parameters(self):
parameters = []
seen = set()
for var, param in self.flow._get_parameters():
if not param.IS_CONFIG_PARAMETER:
continue
# Throw an exception if the parameter is specified twice.
norm = param.name.lower()
if norm in seen:
raise MetaflowException(
"Parameter *%s* is specified twice. "
"Note that parameter names are "
"case-insensitive." % param.name
)
seen.add(norm)
parameters.append(
dict(name=param.name, kv_name=ConfigInput.make_key_name(param.name))
)
return parameters
def _batch(self, node):
attrs = {
# metaflow.user is only used for setting the AWS Job Name.
# Since job executions are no longer tied to a specific user
# identity, we will just set their user to `SFN`. We still do need
# access to the owner of the workflow for production tokens, which
# we can stash in metaflow.owner.
"metaflow.user": "SFN",
"metaflow.owner": self.username,
"metaflow.flow_name": self.flow.name,
"metaflow.step_name": node.name,
# Unfortunately we can't set the task id here since AWS Step
# Functions lacks any notion of run-scoped task identifiers. We
# instead co-opt the AWS Batch job id as the task id. This also
# means that the AWS Batch job name will have missing fields since
# the job id is determined at job execution, but since the job id is
# part of the job description payload, we don't lose much except for
# a few ugly looking black fields in the AWS Batch UI.
# Also, unfortunately we can't set the retry count since
# `$$.State.RetryCount` resolves to an int dynamically and
# AWS Batch job specification only accepts strings. We handle
# retries/catch within AWS Batch to get around this limitation.
# And, we also cannot set the run id here since the run id maps to
# the execution name of the AWS Step Functions State Machine, which
# is different when executing inside a distributed map. We set it once
# in the start step and move it along to be consumed by all the children.
"metaflow.version": self.environment.get_environment_info()[
"metaflow_version"
],
# We rely on step names and task ids of parent steps to construct
# input paths for a task. Since the only information we can pass
# between states (via `InputPath` and `ResultPath`) in AWS Step
# Functions is the job description, we run the risk of exceeding
# 32K state size limit rather quickly if we don't filter the job
# description to a minimal set of fields. Unfortunately, the partial
# `JsonPath` implementation within AWS Step Functions makes this
# work a little non-trivial; it doesn't like dots in keys, so we
# have to add the field again.
# This pattern is repeated in a lot of other places, where we use
# AWS Batch parameters to store AWS Step Functions state
# information, since this field is the only field in the AWS Batch
# specification that allows us to set key-values.
"step_name": node.name,
}
# Store production token within the `start` step, so that subsequent
# `step-functions create` calls can perform a rudimentary authorization
# check.
if node.name == "start":
attrs["metaflow.production_token"] = self.production_token
# Add env vars from the optional @environment decorator.
env_deco = [deco for deco in node.decorators if deco.name == "environment"]
env = {}
if env_deco:
env = env_deco[0].attributes["vars"].copy()
# add METAFLOW_S3_ENDPOINT_URL
if S3_ENDPOINT_URL is not None:
env["METAFLOW_S3_ENDPOINT_URL"] = S3_ENDPOINT_URL
if node.name == "start":
# metaflow.run_id maps to AWS Step Functions State Machine Execution in all
# cases except for when within a for-each construct that relies on
# Distributed Map. To work around this issue, we pass the run id from the
# start step to all subsequent tasks.
attrs["metaflow.run_id.$"] = "$$.Execution.Name"
# Initialize parameters for the flow in the `start` step.
parameters = self._process_parameters()
if parameters:
# Get user-defined parameters from State Machine Input.
# Since AWS Step Functions doesn't allow for optional inputs
# currently, we have to unfortunately place an artificial
# constraint that every parameterized workflow needs to include
# `Parameters` as a key in the input to the workflow.
# `step-functions trigger` already takes care of this
# requirement, but within the UI, the users will be required to
# specify an input with key as `Parameters` and value as a
# stringified json of the actual parameters -
# {"Parameters": "{\"alpha\": \"beta\"}"}
env["METAFLOW_PARAMETERS"] = "$.Parameters"
default_parameters = {}
for parameter in parameters:
if parameter["value"] is not None:
default_parameters[parameter["name"]] = parameter["value"]
# Dump the default values specified in the flow.
env["METAFLOW_DEFAULT_PARAMETERS"] = json.dumps(default_parameters)
# `start` step has no upstream input dependencies aside from
# parameters.
input_paths = None
else:
# We need to rely on the `InputPath` of the AWS Step Functions
# specification to grab task ids and the step names of the parent
# to properly construct input_paths at runtime. Thanks to the
# JsonPath-foo embedded in the parent states, we have this
# information easily available.
if node.parallel_foreach:
raise StepFunctionsException(
"Parallel steps are not supported yet with AWS step functions."
)
# Handle foreach join.
if (
node.type == "join"
and self.graph[node.split_parents[-1]].type == "foreach"
):
input_paths = (
"sfn-${METAFLOW_RUN_ID}/%s/:"
"${METAFLOW_PARENT_TASK_IDS}" % node.in_funcs[0]
)
# Unfortunately, AWS Batch only allows strings as value types
# in its specification, and we don't have any way to concatenate
# the task ids array from the parent steps within AWS Step
# Functions and pass it down to AWS Batch. We instead have to
# rely on publishing the state to DynamoDb and fetching it back
# in within the AWS Batch entry point to set
# `METAFLOW_PARENT_TASK_IDS`. The state is scoped to the parent
# foreach task `METAFLOW_SPLIT_PARENT_TASK_ID`. We decided on
# AWS DynamoDb and not AWS Lambdas, because deploying and
# debugging Lambdas would be a nightmare as far as OSS support
# is concerned.
env["METAFLOW_SPLIT_PARENT_TASK_ID"] = (
"$.Parameters.split_parent_task_id_%s" % node.split_parents[-1]
)
# Inherit the run id from the parent and pass it along to children.
attrs["metaflow.run_id.$"] = "$.Parameters.['metaflow.run_id']"
else:
# Set appropriate environment variables for runtime replacement.
if len(node.in_funcs) == 1:
input_paths = (
"sfn-${METAFLOW_RUN_ID}/%s/${METAFLOW_PARENT_TASK_ID}"
% node.in_funcs[0]
)
env["METAFLOW_PARENT_TASK_ID"] = "$.JobId"
# Inherit the run id from the parent and pass it along to children.
attrs["metaflow.run_id.$"] = "$.Parameters.['metaflow.run_id']"
else:
# Generate the input paths in a quasi-compressed format.
# See util.decompress_list for why this is written the way
# it is.
input_paths = "sfn-${METAFLOW_RUN_ID}:" + ",".join(
"/${METAFLOW_PARENT_%s_STEP}/"
"${METAFLOW_PARENT_%s_TASK_ID}" % (idx, idx)
for idx, _ in enumerate(node.in_funcs)
)
# Inherit the run id from the parent and pass it along to children.
attrs["metaflow.run_id.$"] = "$.[0].Parameters.['metaflow.run_id']"
for idx, _ in enumerate(node.in_funcs):
env["METAFLOW_PARENT_%s_TASK_ID" % idx] = "$.[%s].JobId" % idx
env["METAFLOW_PARENT_%s_STEP" % idx] = (
"$.[%s].Parameters.step_name" % idx
)
env["METAFLOW_INPUT_PATHS"] = input_paths
if node.is_inside_foreach:
# Set the task id of the parent job of the foreach split in
# our favorite dumping ground, the AWS Batch attrs. For
# subsequent descendent tasks, this attrs blob becomes the
# input to those descendent tasks. We set and propagate the
# task ids pointing to split_parents through every state.
if any(self.graph[n].type == "foreach" for n in node.in_funcs):
attrs["split_parent_task_id_%s.$" % node.split_parents[-1]] = (
"$.SplitParentTaskId"
)
for parent in node.split_parents[:-1]:
if self.graph[parent].type == "foreach":
attrs["split_parent_task_id_%s.$" % parent] = (
"$.Parameters.split_parent_task_id_%s" % parent
)
elif node.type == "join":
if self.graph[node.split_parents[-1]].type == "foreach":
# A foreach join only gets one set of input from the
# parent tasks. We filter the Map state to only output
# `$.[0]`, since we don't need any of the other outputs,
# that information is available to us from AWS DynamoDB.
# This has a nice side effect of making our foreach
# splits infinitely scalable because otherwise we would
# be bounded by the 32K state limit for the outputs. So,
# instead of referencing `Parameters` fields by index
# (like in `split`), we can just reference them
# directly.
attrs["split_parent_task_id_%s.$" % node.split_parents[-1]] = (
"$.Parameters.split_parent_task_id_%s"
% node.split_parents[-1]
)
for parent in node.split_parents[:-1]:
if self.graph[parent].type == "foreach":
attrs["split_parent_task_id_%s.$" % parent] = (
"$.Parameters.split_parent_task_id_%s" % parent
)
else:
for parent in node.split_parents:
if self.graph[parent].type == "foreach":
attrs["split_parent_task_id_%s.$" % parent] = (
"$.[0].Parameters.split_parent_task_id_%s" % parent
)
else:
for parent in node.split_parents:
if self.graph[parent].type == "foreach":
attrs["split_parent_task_id_%s.$" % parent] = (
"$.Parameters.split_parent_task_id_%s" % parent
)
# Set `METAFLOW_SPLIT_PARENT_TASK_ID_FOR_FOREACH_JOIN` if the
# next transition is to a foreach join, so that the
# stepfunctions decorator can write the mapping for input path
# to DynamoDb.
if any(
self.graph[n].type == "join"
and self.graph[self.graph[n].split_parents[-1]].type == "foreach"
for n in node.out_funcs
):
env["METAFLOW_SPLIT_PARENT_TASK_ID_FOR_FOREACH_JOIN"] = attrs[
"split_parent_task_id_%s.$"
% self.graph[node.out_funcs[0]].split_parents[-1]
]
# Set ttl for the values we set in AWS DynamoDB.
if node.type == "foreach":
if self.workflow_timeout:
env["METAFLOW_SFN_WORKFLOW_TIMEOUT"] = self.workflow_timeout
# Handle split index for for-each.
if any(self.graph[n].type == "foreach" for n in node.in_funcs):
env["METAFLOW_SPLIT_INDEX"] = "$.Index"
env["METAFLOW_CODE_URL"] = self.code_package_url
env["METAFLOW_FLOW_NAME"] = attrs["metaflow.flow_name"]
env["METAFLOW_STEP_NAME"] = attrs["metaflow.step_name"]
env["METAFLOW_RUN_ID"] = attrs["metaflow.run_id.$"]
env["METAFLOW_PRODUCTION_TOKEN"] = self.production_token
env["SFN_STATE_MACHINE"] = self.name
env["METAFLOW_OWNER"] = attrs["metaflow.owner"]
# Can't set `METAFLOW_TASK_ID` due to lack of run-scoped identifiers.
# We will instead rely on `AWS_BATCH_JOB_ID` as the task identifier.
# Can't set `METAFLOW_RETRY_COUNT` either due to integer casting issue.
metadata_env = self.metadata.get_runtime_environment("step-functions")
env.update(metadata_env)
metaflow_version = self.environment.get_environment_info()
metaflow_version["flow_name"] = self.graph.name
metaflow_version["production_token"] = self.production_token
env["METAFLOW_VERSION"] = json.dumps(metaflow_version)
# map config values
cfg_env = {param["name"]: param["kv_name"] for param in self.config_parameters}
if cfg_env:
env["METAFLOW_FLOW_CONFIG_VALUE"] = json.dumps(cfg_env)
# Set AWS DynamoDb Table Name for state tracking for for-eaches.
# There are three instances when metaflow runtime directly interacts
# with AWS DynamoDB.
# 1. To set the cardinality of `foreach`s (which are subsequently)
# read prior to the instantiation of the Map state by AWS Step
# Functions.
# 2. To set the input paths from the parent steps of a foreach join.
# 3. To read the input paths in a foreach join.
if (
node.type == "foreach"
or (
node.is_inside_foreach
and any(
self.graph[n].type == "join"
and self.graph[self.graph[n].split_parents[-1]].type == "foreach"
for n in node.out_funcs
)
)
or (
node.type == "join"
and self.graph[node.split_parents[-1]].type == "foreach"
)
):
if SFN_DYNAMO_DB_TABLE is None:
raise StepFunctionsException(
"An AWS DynamoDB table is needed "
"to support foreach in your flow. "
"You can create one following the "
"instructions listed at *https://a"
"dmin-docs.metaflow.org/metaflow-o"
"n-aws/deployment-guide/manual-dep"
"loyment#scheduling* and "
"re-configure Metaflow using "
"*metaflow configure aws* on your "
"terminal."
)
env["METAFLOW_SFN_DYNAMO_DB_TABLE"] = SFN_DYNAMO_DB_TABLE
# It makes no sense to set env vars to None (shows up as "None" string)
env = {k: v for k, v in env.items() if v is not None}
# Resolve AWS Batch resource requirements.
batch_deco = [deco for deco in node.decorators if deco.name == "batch"][0]
resources = {}
resources.update(batch_deco.attributes)
# Resolve retry strategy.
user_code_retries, total_retries = self._get_retries(node)
task_spec = {
"flow_name": attrs["metaflow.flow_name"],
"step_name": attrs["metaflow.step_name"],
"run_id": "sfn-$METAFLOW_RUN_ID",
# Use AWS Batch job identifier as the globally unique
# task identifier.
"task_id": "$AWS_BATCH_JOB_ID",
# Since retries are handled by AWS Batch, we can rely on
# AWS_BATCH_JOB_ATTEMPT as the job counter.
"retry_count": "$((AWS_BATCH_JOB_ATTEMPT-1))",
}
# merge batch tags supplied through step-fuctions CLI and ones defined in decorator
batch_tags = {**self.aws_batch_tags, **resources["aws_batch_tags"]}
return (
Batch(self.metadata, self.environment, self.flow_datastore)
.create_job(
step_name=node.name,
step_cli=self._step_cli(
node, input_paths, self.code_package_url, user_code_retries
),
task_spec=task_spec,
code_package_metadata=self.code_package_metadata,
code_package_sha=self.code_package_sha,
code_package_url=self.code_package_url,
code_package_ds=self.flow_datastore.TYPE,
image=resources["image"],
queue=resources["queue"],
iam_role=resources["iam_role"],
execution_role=resources["execution_role"],
cpu=resources["cpu"],
gpu=resources["gpu"],
memory=resources["memory"],
run_time_limit=batch_deco.run_time_limit,
shared_memory=resources["shared_memory"],
max_swap=resources["max_swap"],
swappiness=resources["swappiness"],
efa=resources["efa"],
use_tmpfs=resources["use_tmpfs"],
aws_batch_tags=batch_tags,
tmpfs_tempdir=resources["tmpfs_tempdir"],
tmpfs_size=resources["tmpfs_size"],
tmpfs_path=resources["tmpfs_path"],
inferentia=resources["inferentia"],
env=env,
attrs=attrs,
host_volumes=resources["host_volumes"],
efs_volumes=resources["efs_volumes"],
ephemeral_storage=resources["ephemeral_storage"],
log_driver=resources["log_driver"],
log_options=resources["log_options"],
offload_command_to_s3=self.compress_state_machine,
)
.attempts(total_retries + 1)
)
def _get_retries(self, node):
max_user_code_retries = 0
max_error_retries = 0
# Different decorators may have different retrying strategies, so take
# the max of them.
for deco in node.decorators:
user_code_retries, error_retries = deco.step_task_retry_count()
max_user_code_retries = max(max_user_code_retries, user_code_retries)
max_error_retries = max(max_error_retries, error_retries)
return max_user_code_retries, max_user_code_retries + max_error_retries
def _step_cli(self, node, paths, code_package_url, user_code_retries):
cmds = []
script_name = os.path.basename(sys.argv[0])
executable = self.environment.executable(node.name)
if R.use_r():
entrypoint = [R.entrypoint()]
else:
entrypoint = [executable, script_name]
# Use AWS Batch job identifier as the globally unique task identifier.
task_id = "${AWS_BATCH_JOB_ID}"
top_opts_dict = {
"with": [
decorator.make_decorator_spec()
for decorator in node.decorators
if not decorator.statically_defined and decorator.inserted_by is None
]
}
# FlowDecorators can define their own top-level options. They are
# responsible for adding their own top-level options and values through
# the get_top_level_options() hook. See similar logic in runtime.py.
for deco in flow_decorators(self.flow):
top_opts_dict.update(deco.get_top_level_options())
top_opts = list(dict_to_cli_options(top_opts_dict))
top_level = top_opts + [
"--quiet",
"--metadata=%s" % self.metadata.TYPE,
"--environment=%s" % self.environment.TYPE,
"--datastore=%s" % self.flow_datastore.TYPE,
"--datastore-root=%s" % self.flow_datastore.datastore_root,
"--event-logger=%s" % self.event_logger.TYPE,
"--monitor=%s" % self.monitor.TYPE,
"--no-pylint",
"--with=step_functions_internal",
]
if node.name == "start":
# We need a separate unique ID for the special _parameters task
task_id_params = "%s-params" % task_id
# Export user-defined parameters into runtime environment
param_file = "".join(
random.choice(string.ascii_lowercase) for _ in range(10)
)
export_params = (
"python -m "
"metaflow.plugins.aws.step_functions.set_batch_environment "
"parameters %s && . `pwd`/%s" % (param_file, param_file)
)
params = (
entrypoint
+ top_level
+ [
"init",
"--run-id sfn-$METAFLOW_RUN_ID",
"--task-id %s" % task_id_params,
]
)
# Assign tags to run objects.
if self.tags:
params.extend("--tag %s" % tag for tag in self.tags)
# If the start step gets retried, we must be careful not to
# regenerate multiple parameters tasks. Hence, we check first if
# _parameters exists already.
exists = entrypoint + [
"dump",
"--max-value-size=0",
"sfn-${METAFLOW_RUN_ID}/_parameters/%s" % (task_id_params),
]
cmd = "if ! %s >/dev/null 2>/dev/null; then %s && %s; fi" % (
" ".join(exists),
export_params,
" ".join(params),
)
cmds.append(cmd)
paths = "sfn-${METAFLOW_RUN_ID}/_parameters/%s" % (task_id_params)
if node.type == "join" and self.graph[node.split_parents[-1]].type == "foreach":
parent_tasks_file = "".join(
random.choice(string.ascii_lowercase) for _ in range(10)
)
export_parent_tasks = (
"python -m "
"metaflow.plugins.aws.step_functions.set_batch_environment "
"parent_tasks %s && . `pwd`/%s" % (parent_tasks_file, parent_tasks_file)
)
cmds.append(export_parent_tasks)
step = [
"step",
node.name,
"--run-id sfn-$METAFLOW_RUN_ID",
"--task-id %s" % task_id,
# Since retries are handled by AWS Batch, we can rely on
# AWS_BATCH_JOB_ATTEMPT as the job counter.
"--retry-count $((AWS_BATCH_JOB_ATTEMPT-1))",
"--max-user-code-retries %d" % user_code_retries,
"--input-paths %s" % paths,
]
if any(self.graph[n].type == "foreach" for n in node.in_funcs):
# We set the `METAFLOW_SPLIT_INDEX` through JSONPath-foo
# to pass the state from the parent DynamoDb state for for-each.
step.append("--split-index $METAFLOW_SPLIT_INDEX")
if self.tags:
step.extend("--tag %s" % tag for tag in self.tags)
if self.namespace is not None:
step.append("--namespace=%s" % self.namespace)
cmds.append(" ".join(entrypoint + top_level + step))
return " && ".join(cmds)
| StepFunctions |
python | kamyu104__LeetCode-Solutions | Python/sort-integers-by-the-power-value.py | {
"start": 56,
"end": 1823
} | class ____(object):
dp = {}
def getKth(self, lo, hi, k):
"""
:type lo: int
:type hi: int
:type k: int
:rtype: int
"""
def nth_element(nums, n, compare=lambda a, b: a < b):
def partition_around_pivot(left, right, pivot_idx, nums, compare):
new_pivot_idx = left
nums[pivot_idx], nums[right] = nums[right], nums[pivot_idx]
for i in xrange(left, right):
if compare(nums[i], nums[right]):
nums[i], nums[new_pivot_idx] = nums[new_pivot_idx], nums[i]
new_pivot_idx += 1
nums[right], nums[new_pivot_idx] = nums[new_pivot_idx], nums[right]
return new_pivot_idx
left, right = 0, len(nums) - 1
while left <= right:
pivot_idx = random.randint(left, right)
new_pivot_idx = partition_around_pivot(left, right, pivot_idx, nums, compare)
if new_pivot_idx == n:
return
elif new_pivot_idx > n:
right = new_pivot_idx - 1
else: # new_pivot_idx < n
left = new_pivot_idx + 1
def power_value(x):
y, result = x, 0
while x > 1 and x not in Solution.dp:
result += 1
if x%2:
x = 3*x + 1
else:
x //= 2
Solution.dp[y] = result + (Solution.dp[x] if x > 1 else 0)
return Solution.dp[y], y
arr = map(power_value, range(lo, hi+1))
nth_element(arr, k-1)
return arr[k-1][1]
# Time: O(nlogn)
# Space: O(n)
| Solution |
python | bokeh__bokeh | src/bokeh/models/widgets/pickers.py | {
"start": 9274,
"end": 9868
} | class ____(PickerBase, DateCommon, TimeCommon):
""" Bases for various calendar-based datetime picker widgets.
"""
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
min_date = Nullable(Either(Datetime, Date), default=None, help="""
Optional earliest allowable date and time.
""")
max_date = Nullable(Either(Datetime, Date), default=None, help="""
Optional latest allowable date and time.
""")
date_format = Override(default="Y-m-d H:i")
| BaseDatetimePicker |
python | huggingface__transformers | src/transformers/models/audio_spectrogram_transformer/modeling_audio_spectrogram_transformer.py | {
"start": 14966,
"end": 15663
} | class ____(nn.Module):
def __init__(self, config: ASTConfig):
super().__init__()
self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
self.dense = nn.Linear(config.hidden_size, config.num_labels) if config.num_labels > 0 else nn.Identity()
def forward(self, hidden_state):
hidden_state = self.layernorm(hidden_state)
hidden_state = self.dense(hidden_state)
return hidden_state
@auto_docstring(
custom_intro="""
Audio Spectrogram Transformer model with an audio classification head on top (a linear layer on top of the pooled
output) e.g. for datasets like AudioSet, Speech Commands v2.
"""
)
| ASTMLPHead |
python | skorch-dev__skorch | skorch/tests/test_cli.py | {
"start": 521,
"end": 13395
} | class ____:
@pytest.fixture
def resolve_dotted_name(self):
from skorch.cli import _resolve_dotted_name
return _resolve_dotted_name
@pytest.mark.parametrize('name, expected', [
(0, 0),
(1.23, 1.23),
('foo', 'foo'),
('math.cos', cos),
('torch.nn', nn),
('torch.nn.ReLU', nn.ReLU),
])
def test_resolve_dotted_name(self, resolve_dotted_name, name, expected):
result = resolve_dotted_name(name)
assert result == expected
def test_resolve_dotted_name_instantiated(self, resolve_dotted_name):
result = resolve_dotted_name('torch.nn.RReLU(0.123, upper=0.456)')
assert isinstance(result, RReLU)
assert np.isclose(result.lower, 0.123)
assert np.isclose(result.upper, 0.456)
@pytest.fixture
def parse_net_kwargs(self):
from skorch.cli import parse_net_kwargs
return parse_net_kwargs
def test_parse_net_kwargs(self, parse_net_kwargs):
kwargs = {
'lr': 0.05,
'max_epochs': 5,
'module__num_units': 10,
'module__nonlin': 'torch.nn.RReLU(0.123, upper=0.456)',
}
parsed_kwargs = parse_net_kwargs(kwargs)
assert len(parsed_kwargs) == 4
assert np.isclose(parsed_kwargs['lr'], 0.05)
assert parsed_kwargs['max_epochs'] == 5
assert parsed_kwargs['module__num_units'] == 10
assert isinstance(parsed_kwargs['module__nonlin'], RReLU)
assert np.isclose(parsed_kwargs['module__nonlin'].lower, 0.123)
assert np.isclose(parsed_kwargs['module__nonlin'].upper, 0.456)
@pytest.fixture
def net_cls(self):
from skorch import NeuralNetClassifier
return NeuralNetClassifier
@pytest.fixture
def net(self, net_cls, classifier_module):
return net_cls(classifier_module)
@pytest.fixture
def pipe(self, net):
return Pipeline([
('features', FeatureUnion([
('scale', MinMaxScaler()),
])),
('net', net),
])
@pytest.fixture
def yield_estimators(self):
from skorch.cli import _yield_estimators
return _yield_estimators
def test_yield_estimators_net(self, yield_estimators, net):
result = list(yield_estimators(net))
assert result[0][0] == ''
assert result[0][1] is net
assert result[1][0] == 'module'
assert result[1][1] is net.module
def test_yield_estimators_pipe(self, yield_estimators, pipe):
result = list(yield_estimators(pipe))
scaler = pipe.named_steps['features'].transformer_list[0][1]
net = pipe.named_steps['net']
module = net.module
assert result[0][0] == 'features__scale'
assert result[0][1] is scaler
assert result[1][0] == 'net'
assert result[1][1] is net
assert result[2][0] == 'net__module'
assert result[2][1] is module
@pytest.fixture
def substitute_default(self):
from skorch.cli import _substitute_default
return _substitute_default
@pytest.mark.parametrize('s, new_value, expected', [
('', '', ''),
('', 'foo', ''),
('bar', 'foo', 'bar'),
('int (default=128)', '', 'int (default=)'),
('int (default=128)', None, 'int (default=128)'),
('int (default=128)', '""', 'int (default="")'),
('int (default=128)', '128', 'int (default=128)'),
('int (default=128)', '256', 'int (default=256)'),
('int (default=128)', 256, 'int (default=256)'),
('with_parens (default=(1, 2))', (3, 4), 'with_parens (default=(3, 4))'),
('int (default =128)', '256', 'int (default =256)'),
('int (default= 128)', '256', 'int (default= 256)'),
('int (default = 128)', '256', 'int (default = 256)'),
(
'nonlin (default = ReLU())',
nn.Hardtanh(1, 2),
'nonlin (default = {})'.format(nn.Hardtanh(1, 2))
),
(
# from sklearn MinMaxScaler
'tuple (min, max), default=(0, 1)',
(-1, 1),
'tuple (min, max), default=(-1, 1)'
),
(
# from sklearn MinMaxScaler
'boolean, optional, default True',
False,
'boolean, optional, default False'
),
(
# from sklearn Normalizer
"'l1', 'l2', or 'max', optional ('l2' by default)",
'l1',
"'l1', 'l2', or 'max', optional ('l1' by default)"
),
(
# same but double ticks
'"l1", "l2", or "max", optional ("l2" by default)',
'l1',
'"l1", "l2", or "max", optional ("l1" by default)'
),
(
# same but no ticks
"l1, l2, or max, optional (l2 by default)",
'l1',
"l1, l2, or max, optional (l1 by default)"
),
(
"tuple, optional ((1, 1) by default)",
(2, 2),
"tuple, optional ((2, 2) by default)"
),
(
"nonlin (ReLU() by default)",
nn.Tanh(),
"nonlin (Tanh() by default)"
),
])
def test_replace_default(self, substitute_default, s, new_value, expected):
result = substitute_default(s, new_value)
assert result == expected
@pytest.fixture
def print_help(self):
from skorch.cli import print_help
return print_help
def test_print_help_net(self, print_help, net, capsys):
print_help(net)
out = capsys.readouterr()[0]
expected_snippets = [
'-- --help',
'<NeuralNetClassifier> options',
'--module : torch module (class or instance)',
'--batch_size : int (default=128)',
'<MLPModule> options',
'--module__hidden_units : int (default=10)'
]
for snippet in expected_snippets:
assert snippet in out
def test_print_help_net_custom_defaults(self, print_help, net, capsys):
defaults = {'batch_size': 256, 'module__hidden_units': 55}
print_help(net, defaults)
out = capsys.readouterr()[0]
expected_snippets = [
'-- --help',
'<NeuralNetClassifier> options',
'--module : torch module (class or instance)',
'--batch_size : int (default=256)',
'<MLPModule> options',
'--module__hidden_units : int (default=55)'
]
for snippet in expected_snippets:
assert snippet in out
def test_print_help_pipeline(self, print_help, pipe, capsys):
print_help(pipe)
out = capsys.readouterr()[0]
expected_snippets = [
'-- --help',
'<MinMaxScaler> options',
'--features__scale__feature_range',
'<NeuralNetClassifier> options',
'--net__module : torch module (class or instance)',
'--net__batch_size : int (default=128)',
'<MLPModule> options',
'--net__module__hidden_units : int (default=10)'
]
for snippet in expected_snippets:
assert snippet in out
def test_print_help_pipeline_custom_defaults(
self, print_help, pipe, capsys):
defaults = {'net__batch_size': 256, 'net__module__hidden_units': 55}
print_help(pipe, defaults=defaults)
out = capsys.readouterr()[0]
expected_snippets = [
'-- --help',
'<MinMaxScaler> options',
'--features__scale__feature_range',
'<NeuralNetClassifier> options',
'--net__module : torch module (class or instance)',
'--net__batch_size : int (default=256)',
'<MLPModule> options',
'--net__module__hidden_units : int (default=55)'
]
for snippet in expected_snippets:
assert snippet in out
@pytest.fixture
def clf_sklearn(self):
from sklearn.linear_model import LinearRegression
return LinearRegression()
@pytest.fixture
def pipe_sklearn(self, clf_sklearn):
return Pipeline([
('features', FeatureUnion([
('scale', MinMaxScaler()),
])),
('clf', clf_sklearn),
])
def test_print_help_sklearn_estimator(self, print_help, clf_sklearn, capsys):
# Should also work with non-skorch sklearn estimator;
# need to assert that count==1 since there was a bug in my
# first implementation that resulted in the help for the final
# estimator appearing twice.
print_help(clf_sklearn)
out = capsys.readouterr()[0]
expected_snippets = [
'-- --help',
'--fit_intercept',
'--copy_X',
]
for snippet in expected_snippets:
assert snippet in out
assert out.count(snippet) == 1
def test_print_help_sklearn_pipeline(self, print_help, pipe_sklearn, capsys):
# Should also work with non-skorch sklearn pipelines;
# need to assert that count==1 since there was a bug in my
# first implementation that resulted in the help for the final
# estimator appearing twice.
print_help(pipe_sklearn)
out = capsys.readouterr()[0]
expected_snippets = [
'-- --help',
'<MinMaxScaler> options',
'--features__scale__feature_range',
'--clf__fit_intercept',
]
for snippet in expected_snippets:
assert snippet in out
assert out.count(snippet) == 1
@pytest.fixture
def parse_args(self):
from skorch.cli import parse_args
return parse_args
@pytest.fixture
def estimator(self, net_cls):
mock = Mock(net_cls)
return mock
def test_parse_args_help(self, parse_args, estimator):
with patch('skorch.cli.sys.exit') as exit_:
with patch('skorch.cli.print_help') as help_:
parsed = parse_args({'help': True, 'foo': 'bar'})
parsed(estimator)
assert estimator.set_params.call_count == 0 # kwargs and defaults
assert help_.call_count == 1
assert exit_.call_count == 1
def test_parse_args_run(self, parse_args, estimator):
kwargs = {'foo': 'bar', 'baz': 'math.cos'}
with patch('skorch.cli.sys.exit') as exit_:
with patch('skorch.cli.print_help') as help_:
parsed = parse_args(kwargs)
parsed(estimator)
assert estimator.set_params.call_count == 2 # defaults and kwargs
defaults_set_params = estimator.set_params.call_args_list[0][1]
assert not defaults_set_params # no defaults specified
kwargs_set_params = estimator.set_params.call_args_list[1][1]
assert kwargs_set_params['foo'] == 'bar'
# pylint: disable=comparison-with-callable
assert kwargs_set_params['baz'] == cos
assert help_.call_count == 0
assert exit_.call_count == 0
def test_parse_args_net_custom_defaults(self, parse_args, net):
defaults = {'batch_size': 256, 'module__hidden_units': 55}
kwargs = {'batch_size': 123, 'module__nonlin': nn.Hardtanh(1, 2)}
parsed = parse_args(kwargs, defaults)
net = parsed(net)
# cmd line args have precedence over defaults
assert net.batch_size == 123
assert net.module__hidden_units == 55
assert isinstance(net.module__nonlin, nn.Hardtanh)
assert net.module__nonlin.min_val == 1
assert net.module__nonlin.max_val == 2
def test_parse_args_pipe_custom_defaults(self, parse_args, pipe):
defaults = {'net__batch_size': 256, 'net__module__hidden_units': 55}
kwargs = {'net__batch_size': 123, 'net__module__nonlin': nn.Hardtanh(1, 2)}
parsed = parse_args(kwargs, defaults)
pipe = parsed(pipe)
net = pipe.steps[-1][1]
# cmd line args have precedence over defaults
assert net.batch_size == 123
assert net.module__hidden_units == 55
assert isinstance(net.module__nonlin, nn.Hardtanh)
assert net.module__nonlin.min_val == 1
assert net.module__nonlin.max_val == 2
def test_parse_args_sklearn_pipe_custom_defaults(self, parse_args, pipe_sklearn):
defaults = {'features__scale__copy': 123, 'clf__fit_intercept': 456}
kwargs = {'features__scale__copy': 555, 'clf__n_jobs': 5}
parsed = parse_args(kwargs, defaults)
pipe = parsed(pipe_sklearn)
scaler = pipe.steps[0][1].transformer_list[0][1]
clf = pipe.steps[-1][1]
# cmd line args have precedence over defaults
assert scaler.copy == 555
assert clf.fit_intercept == 456
assert clf.n_jobs == 5
| TestCli |
python | walkccc__LeetCode | solutions/2227. Encrypt and Decrypt Strings/2227.py | {
"start": 108,
"end": 1293
} | class ____:
def __init__(self, keys: list[str], values: list[str], dictionary: list[str]):
self.keyToValue = {k: v for k, v in zip(keys, values)}
self.valueToKeys = collections.defaultdict(list)
self.root = TrieNode()
for k, v in zip(keys, values):
self.valueToKeys[v].append(k)
for word in dictionary:
self._insert(word)
def encrypt(self, word1: str) -> str:
return ''.join(self.keyToValue[c] for c in word1)
def decrypt(self, word2: str) -> int:
return self._find(word2, 0, self.root)
def _insert(self, word: str) -> None:
node = self.root
for c in word:
node = node.children.setdefault(c, TrieNode())
node.isWord = True
def _find(self, word: str, i: int, node: TrieNode) -> int:
value = word[i:i + 2]
if value not in self.valueToKeys:
return 0
ans = 0
if i + 2 == len(word):
for key in self.valueToKeys[value]:
if key in node.children and node.children[key].isWord:
ans += 1
return ans
for key in self.valueToKeys[value]:
if key not in node.children:
continue
ans += self._find(word, i + 2, node.children[key])
return ans
| Encrypter |
python | pyqtgraph__pyqtgraph | benchmarks/arrayToQPath.py | {
"start": 80,
"end": 734
} | class ____:
param_names = ["Size", "Connection Type"]
params = ([10_000, 100_000, 1_000_000], ['all', 'finite', 'pairs', 'array'])
def setup(self, nelems, connect):
self.xdata = np.arange(nelems, dtype=np.float64)
self.ydata = rng.standard_normal(nelems, dtype=np.float64)
if connect == 'array':
self.connect_array = np.ones(nelems, dtype=bool)
if self.have_nonfinite:
self.ydata[::5000] = np.nan
def time_test(self, nelems, connect):
if connect == 'array':
connect = self.connect_array
pg.arrayToQPath(self.xdata, self.ydata, connect=connect)
| _TimeSuite |
python | walkccc__LeetCode | solutions/2307. Check for Contradictions in Equations/2307.py | {
"start": 0,
"end": 871
} | class ____:
def checkContradictions(
self,
equations: list[list[str]],
values: list[float],
) -> bool:
# Convert `string` to `int` for a better perfermance.
strToInt = {}
for u, v in equations:
strToInt.setdefault(u, len(strToInt))
strToInt.setdefault(v, len(strToInt))
graph = [[] for _ in range(len(strToInt))]
seen = [0.0] * len(graph)
for i, ((A, B), value) in enumerate(zip(equations, values)):
u = strToInt[A]
v = strToInt[B]
graph[u].append((v, value))
graph[v].append((u, 1 / value))
def dfs(u: int, val: float) -> bool:
if seen[u]:
return abs(val / seen[u] - 1) > 1e-5
seen[u] = val
return any(dfs(v, val / w) for v, w in graph[u])
for i in range(len(graph)):
if not seen[i] and dfs(i, 1.0):
return True
return False
| Solution |
python | PyCQA__pylint | tests/functional/s/slots_checks.py | {
"start": 2704,
"end": 2831
} | class ____:
__slots__ = ("a", "b")
a: int
b: str
c: bool # [declare-non-slot]
| ClassTypeHintNotInSlotsWithoutDict |
python | ethereum__web3.py | web3/providers/async_base.py | {
"start": 5579,
"end": 8156
} | class ____(AsyncBaseProvider):
def __init__(self, **kwargs: Any) -> None:
super().__init__(**kwargs)
self.request_counter = itertools.count()
def form_request(self, method: RPCEndpoint, params: Any = None) -> RPCRequest:
request_id = next(self.request_counter)
rpc_dict = {
"id": request_id,
"jsonrpc": "2.0",
"method": method,
"params": params or [],
}
return cast(RPCRequest, rpc_dict)
@staticmethod
def encode_rpc_dict(rpc_dict: RPCRequest) -> bytes:
encoded = FriendlyJsonSerde().json_encode(
cast(dict[str, Any], rpc_dict), cls=Web3JsonEncoder
)
return to_bytes(text=encoded)
def encode_rpc_request(self, method: RPCEndpoint, params: Any) -> bytes:
rpc_dict = self.form_request(method, params)
return self.encode_rpc_dict(rpc_dict)
@staticmethod
def decode_rpc_response(raw_response: bytes) -> RPCResponse:
text_response = str(
to_text(raw_response) if not is_text(raw_response) else raw_response
)
return cast(RPCResponse, FriendlyJsonSerde().json_decode(text_response))
async def is_connected(self, show_traceback: bool = False) -> bool:
try:
response = await self.make_request(RPCEndpoint("web3_clientVersion"), [])
except (OSError, ProviderConnectionError) as e:
if show_traceback:
raise ProviderConnectionError(
f"Problem connecting to provider with error: {type(e)}: {e}"
)
return False
if "error" in response:
if show_traceback:
raise ProviderConnectionError(
f"Error received from provider: {response}"
)
return False
if response.get("jsonrpc") == "2.0":
return True
else:
if show_traceback:
raise ProviderConnectionError(f"Bad jsonrpc version: {response}")
return False
# -- batch requests -- #
def encode_batch_rpc_request(
self, requests: list[tuple[RPCEndpoint, Any]]
) -> bytes:
return (
b"["
+ b", ".join(
self.encode_rpc_request(method, params) for method, params in requests
)
+ b"]"
)
def encode_batch_request_dicts(self, request_dicts: list[RPCRequest]) -> bytes:
return b"[" + b",".join(self.encode_rpc_dict(d) for d in request_dicts) + b"]"
| AsyncJSONBaseProvider |
python | huggingface__transformers | src/transformers/models/deepseek_vl/modular_deepseek_vl.py | {
"start": 4556,
"end": 5141
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
in_features = config.vision_config.hidden_size
out_features = config.text_config.hidden_size
self.linear1 = nn.Linear(in_features, out_features)
self.activation = nn.GELU()
self.linear2 = nn.Linear(out_features, out_features)
def forward(self, vision_encodings: torch.Tensor) -> torch.Tensor:
x = self.linear1(vision_encodings)
x = self.activation(x)
x = self.linear2(x)
return x
| DeepseekVLAligner |
python | charliermarsh__ruff | crates/ruff_python_formatter/resources/test/fixtures/ruff/statement/class_definition.py | {
"start": 1564,
"end": 1598
} | class ____( # comment
):
pass
| C |
python | sqlalchemy__sqlalchemy | test/orm/test_joins.py | {
"start": 80762,
"end": 84092
} | class ____(fixtures.MappedTest, AssertsCompiledSQL):
"""test joins to an aliased selectable and that we can refer to that
aliased selectable in filter criteria.
Basically testing that the aliasing Query applies to with_polymorphic
targets doesn't leak into non-polymorphic mappers.
"""
__dialect__ = "default"
run_create_tables = None
run_deletes = None
@classmethod
def define_tables(cls, metadata):
Table(
"parent",
metadata,
Column("id", Integer, primary_key=True),
Column("data", String(50)),
)
Table(
"child",
metadata,
Column("id", Integer, primary_key=True),
Column("parent_id", Integer, ForeignKey("parent.id")),
Column("data", String(50)),
)
@classmethod
def setup_mappers(cls):
parent, child = cls.tables.parent, cls.tables.child
class Parent(cls.Comparable):
pass
class Child(cls.Comparable):
pass
mp = cls.mapper_registry.map_imperatively(Parent, parent)
cls.mapper_registry.map_imperatively(Child, child)
derived = select(child).alias()
npc = aliased(Child, derived)
cls.npc = npc
cls.derived = derived
mp.add_property("npc", relationship(npc))
def test_join_parent_child(self):
Parent = self.classes.Parent
sess = fixture_session()
self.assert_compile(
sess.query(Parent)
.join(Parent.npc)
.filter(self.derived.c.data == "x"),
"SELECT parent.id AS parent_id, parent.data AS parent_data "
"FROM parent JOIN (SELECT child.id AS id, "
"child.parent_id AS parent_id, "
"child.data AS data "
"FROM child) AS anon_1 ON parent.id = anon_1.parent_id "
"WHERE anon_1.data = :data_1",
)
def test_join_parent_child_select_from(self):
Parent = self.classes.Parent
npc = self.npc
sess = fixture_session()
self.assert_compile(
sess.query(npc)
.select_from(Parent)
.join(Parent.npc)
.filter(self.derived.c.data == "x"),
"SELECT anon_1.id AS anon_1_id, anon_1.parent_id "
"AS anon_1_parent_id, anon_1.data AS anon_1_data "
"FROM parent JOIN (SELECT child.id AS id, child.parent_id AS "
"parent_id, child.data AS data FROM child) AS anon_1 ON "
"parent.id = anon_1.parent_id WHERE anon_1.data = :data_1",
)
def test_join_select_parent_child(self):
Parent = self.classes.Parent
npc = self.npc
sess = fixture_session()
self.assert_compile(
sess.query(Parent, npc)
.join(Parent.npc)
.filter(self.derived.c.data == "x"),
"SELECT parent.id AS parent_id, parent.data AS parent_data, "
"anon_1.id AS anon_1_id, anon_1.parent_id AS anon_1_parent_id, "
"anon_1.data AS anon_1_data FROM parent JOIN "
"(SELECT child.id AS id, child.parent_id AS parent_id, "
"child.data AS data FROM child) AS anon_1 ON parent.id = "
"anon_1.parent_id WHERE anon_1.data = :data_1",
)
| JoinToNonPolyAliasesTest |
python | tensorflow__tensorflow | tensorflow/python/eager/benchmarks/resnet50/resnet50.py | {
"start": 2927,
"end": 5507
} | class ____(tf.keras.Model):
"""_ConvBlock is the block that has a conv layer at shortcut.
Args:
kernel_size: the kernel size of middle conv layer at main path
filters: list of integers, the filters of 3 conv layer at main path
stage: integer, current stage label, used for generating layer names
block: 'a','b'..., current block label, used for generating layer names
data_format: data_format for the input ('channels_first' or
'channels_last').
strides: strides for the convolution. Note that from stage 3, the first
conv layer at main path is with strides=(2,2), and the shortcut should
have strides=(2,2) as well.
"""
def __init__(self,
kernel_size,
filters,
stage,
block,
data_format,
strides=(2, 2)):
super(_ConvBlock, self).__init__(name='')
filters1, filters2, filters3 = filters
conv_name_base = 'res' + str(stage) + block + '_branch'
bn_name_base = 'bn' + str(stage) + block + '_branch'
bn_axis = 1 if data_format == 'channels_first' else 3
self.conv2a = layers.Conv2D(
filters1, (1, 1),
strides=strides,
name=conv_name_base + '2a',
data_format=data_format)
self.bn2a = layers.BatchNormalization(
axis=bn_axis, name=bn_name_base + '2a')
self.conv2b = layers.Conv2D(
filters2,
kernel_size,
padding='same',
name=conv_name_base + '2b',
data_format=data_format)
self.bn2b = layers.BatchNormalization(
axis=bn_axis, name=bn_name_base + '2b')
self.conv2c = layers.Conv2D(
filters3, (1, 1), name=conv_name_base + '2c', data_format=data_format)
self.bn2c = layers.BatchNormalization(
axis=bn_axis, name=bn_name_base + '2c')
self.conv_shortcut = layers.Conv2D(
filters3, (1, 1),
strides=strides,
name=conv_name_base + '1',
data_format=data_format)
self.bn_shortcut = layers.BatchNormalization(
axis=bn_axis, name=bn_name_base + '1')
def call(self, input_tensor, training=False):
x = self.conv2a(input_tensor)
x = self.bn2a(x, training=training)
x = tf.nn.relu(x)
x = self.conv2b(x)
x = self.bn2b(x, training=training)
x = tf.nn.relu(x)
x = self.conv2c(x)
x = self.bn2c(x, training=training)
shortcut = self.conv_shortcut(input_tensor)
shortcut = self.bn_shortcut(shortcut, training=training)
x += shortcut
return tf.nn.relu(x)
# pylint: disable=not-callable
| _ConvBlock |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_image41.py | {
"start": 315,
"end": 1331
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("image41.xlsx")
# Despite a lot of effort and testing I can't match Excel's
# calculations exactly for EMF files. The differences are are small
# (<1%) and in general aren't visible. The following ignore the
# elements where these differences occur until the they can be
# resolved. This issue doesn't occur for any other image type.
self.ignore_elements = {
"xl/drawings/drawing1.xml": ["<xdr:rowOff>", "<xdr:colOff>", "<a:ext cx="]
}
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with image(s)."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
worksheet.insert_image("E9", self.image_dir + "logo.emf")
workbook.close()
self.assertExcelEqual()
| TestCompareXLSXFiles |
python | fluentpython__example-code-2e | 21-async/mojifinder/bottle.py | {
"start": 118528,
"end": 125016
} | class ____(ServerAdapter):
""" Untested. """
adapters = [WaitressServer, PasteServer, TwistedServer, CherryPyServer, WSGIRefServer]
def run(self, handler):
for sa in self.adapters:
try:
return sa(self.host, self.port, **self.options).run(handler)
except ImportError:
pass
server_names = {
'cgi': CGIServer,
'flup': FlupFCGIServer,
'wsgiref': WSGIRefServer,
'waitress': WaitressServer,
'cherrypy': CherryPyServer,
'paste': PasteServer,
'fapws3': FapwsServer,
'tornado': TornadoServer,
'gae': AppEngineServer,
'twisted': TwistedServer,
'diesel': DieselServer,
'meinheld': MeinheldServer,
'gunicorn': GunicornServer,
'eventlet': EventletServer,
'gevent': GeventServer,
'geventSocketIO':GeventSocketIOServer,
'rocket': RocketServer,
'bjoern' : BjoernServer,
'auto': AutoServer,
}
###############################################################################
# Application Control ##########################################################
###############################################################################
def load(target, **namespace):
""" Import a module or fetch an object from a module.
* ``package.module`` returns `module` as a module object.
* ``pack.mod:name`` returns the module variable `name` from `pack.mod`.
* ``pack.mod:func()`` calls `pack.mod.func()` and returns the result.
The last form accepts not only function calls, but any type of
expression. Keyword arguments passed to this function are available as
local variables. Example: ``import_string('re:compile(x)', x='[a-z]')``
"""
module, target = target.split(":", 1) if ':' in target else (target, None)
if module not in sys.modules: __import__(module)
if not target: return sys.modules[module]
if target.isalnum(): return getattr(sys.modules[module], target)
package_name = module.split('.')[0]
namespace[package_name] = sys.modules[package_name]
return eval('%s.%s' % (module, target), namespace)
def load_app(target):
""" Load a bottle application from a module and make sure that the import
does not affect the current default application, but returns a separate
application object. See :func:`load` for the target parameter. """
global NORUN; NORUN, nr_old = True, NORUN
try:
tmp = default_app.push() # Create a new "default application"
rv = load(target) # Import the target module
return rv if callable(rv) else tmp
finally:
default_app.remove(tmp) # Remove the temporary added default application
NORUN = nr_old
_debug = debug
def run(app=None, server='wsgiref', host='127.0.0.1', port=8080,
interval=1, reloader=False, quiet=False, plugins=None,
debug=None, **kargs):
""" Start a server instance. This method blocks until the server terminates.
:param app: WSGI application or target string supported by
:func:`load_app`. (default: :func:`default_app`)
:param server: Server adapter to use. See :data:`server_names` keys
for valid names or pass a :class:`ServerAdapter` subclass.
(default: `wsgiref`)
:param host: Server address to bind to. Pass ``0.0.0.0`` to listens on
all interfaces including the external one. (default: 127.0.0.1)
:param port: Server port to bind to. Values below 1024 require root
privileges. (default: 8080)
:param reloader: Start auto-reloading server? (default: False)
:param interval: Auto-reloader interval in seconds (default: 1)
:param quiet: Suppress output to stdout and stderr? (default: False)
:param options: Options passed to the server adapter.
"""
if NORUN: return
if reloader and not os.environ.get('BOTTLE_CHILD'):
try:
lockfile = None
fd, lockfile = tempfile.mkstemp(prefix='bottle.', suffix='.lock')
os.close(fd) # We only need this file to exist. We never write to it
while os.path.exists(lockfile):
args = [sys.executable] + sys.argv
environ = os.environ.copy()
environ['BOTTLE_CHILD'] = 'true'
environ['BOTTLE_LOCKFILE'] = lockfile
p = subprocess.Popen(args, env=environ)
while p.poll() is None: # Busy wait...
os.utime(lockfile, None) # I am alive!
time.sleep(interval)
if p.poll() != 3:
if os.path.exists(lockfile): os.unlink(lockfile)
sys.exit(p.poll())
except KeyboardInterrupt:
pass
finally:
if os.path.exists(lockfile):
os.unlink(lockfile)
return
try:
if debug is not None: _debug(debug)
app = app or default_app()
if isinstance(app, basestring):
app = load_app(app)
if not callable(app):
raise ValueError("Application is not callable: %r" % app)
for plugin in plugins or []:
app.install(plugin)
if server in server_names:
server = server_names.get(server)
if isinstance(server, basestring):
server = load(server)
if isinstance(server, type):
server = server(host=host, port=port, **kargs)
if not isinstance(server, ServerAdapter):
raise ValueError("Unknown or unsupported server: %r" % server)
server.quiet = server.quiet or quiet
if not server.quiet:
_stderr("Bottle v%s server starting up (using %s)...\n" % (__version__, repr(server)))
_stderr("Listening on http://%s:%d/\n" % (server.host, server.port))
_stderr("Hit Ctrl-C to quit.\n\n")
if reloader:
lockfile = os.environ.get('BOTTLE_LOCKFILE')
bgcheck = FileCheckerThread(lockfile, interval)
with bgcheck:
server.run(app)
if bgcheck.status == 'reload':
sys.exit(3)
else:
server.run(app)
except KeyboardInterrupt:
pass
except (SystemExit, MemoryError):
raise
except:
if not reloader: raise
if not getattr(server, 'quiet', quiet):
print_exc()
time.sleep(interval)
sys.exit(3)
| AutoServer |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_orcid.py | {
"start": 503,
"end": 1600
} | class ____(ColumnMapMetricProvider):
# This is the id string that will be used to reference your metric.
condition_metric_name = "column_values.valid_orcid"
# This method implements the core logic for the PandasExecutionEngine
@column_condition_partial(engine=PandasExecutionEngine)
def _pandas(cls, column, **kwargs):
def matches_orcid_regex(x):
return bool(re.match(ORCID_REGEX, str(x)))
return column.apply(lambda x: matches_orcid_regex(x) if x else False)
# This method defines the business logic for evaluating your metric when using a SqlAlchemyExecutionEngine
# @column_condition_partial(engine=SqlAlchemyExecutionEngine)
# def _sqlalchemy(cls, column, _dialect, **kwargs):
# raise NotImplementedError
# This method defines the business logic for evaluating your metric when using a SparkDFExecutionEngine
# @column_condition_partial(engine=SparkDFExecutionEngine)
# def _spark(cls, column, **kwargs):
# raise NotImplementedError
# This class defines the Expectation itself
| ColumnValuesToBeValidOrcid |
python | getsentry__sentry | src/sentry/hybridcloud/outbox/category.py | {
"start": 12575,
"end": 12883
} | class ____(IntEnum):
SLACK = 0
GITHUB = 1
JIRA = 2
GITLAB = 3
MSTEAMS = 4
BITBUCKET = 5
VSTS = 6
JIRA_SERVER = 7
GITHUB_ENTERPRISE = 8
BITBUCKET_SERVER = 9
LEGACY_PLUGIN = 10
GETSENTRY = 11
DISCORD = 12
VERCEL = 13
GOOGLE = 14
| WebhookProviderIdentifier |
python | pytorch__pytorch | torch/package/package_importer.py | {
"start": 29600,
"end": 31727
} | class ____:
"""Private class used to support PackageImporter.get_resource_reader().
Confirms to the importlib.abc.ResourceReader interface. Allowed to access
the innards of PackageImporter.
"""
def __init__(self, importer, fullname):
self.importer = importer
self.fullname = fullname
def open_resource(self, resource):
from io import BytesIO
return BytesIO(self.importer.load_binary(self.fullname, resource))
def resource_path(self, resource):
# The contract for resource_path is that it either returns a concrete
# file system path or raises FileNotFoundError.
if isinstance(
self.importer.zip_reader, DirectoryReader
) and self.importer.zip_reader.has_record(
os.path.join(self.fullname, resource)
):
return os.path.join(
self.importer.zip_reader.directory, self.fullname, resource
)
raise FileNotFoundError
def is_resource(self, name):
path = self.importer._zipfile_path(self.fullname, name)
return self.importer.zip_reader.has_record(path)
def contents(self):
from pathlib import Path
filename = self.fullname.replace(".", "/")
fullname_path = Path(self.importer._zipfile_path(self.fullname))
files = self.importer.zip_reader.get_all_records()
subdirs_seen = set()
for filename in files:
try:
relative = Path(filename).relative_to(fullname_path)
except ValueError:
continue
# If the path of the file (which is relative to the top of the zip
# namespace), relative to the package given when the resource
# reader was created, has a parent, then it's a name in a
# subdirectory and thus we skip it.
parent_name = relative.parent.name
if len(parent_name) == 0:
yield relative.name
elif parent_name not in subdirs_seen:
subdirs_seen.add(parent_name)
yield parent_name
| _PackageResourceReader |
python | sphinx-doc__sphinx | tests/roots/test-ext-autodoc/target/enums.py | {
"start": 5000,
"end": 5158
} | class ____(enum.Enum):
"""this is enum class"""
@property
def name(self):
"""docstring"""
return super().name
| EnumNamePropertyInClass |
python | astropy__astropy | astropy/io/ascii/html.py | {
"start": 6567,
"end": 7771
} | class ____(core.BaseData):
splitter_class = HTMLSplitter
def start_line(self, lines):
"""
Return the line number at which table data begins.
"""
for i, line in enumerate(lines):
if not isinstance(line, SoupString):
raise TypeError("HTML lines should be of type SoupString")
soup = line.soup
if soup.td is not None:
if soup.th is not None:
raise core.InconsistentTableError(
"HTML tables cannot have headings and data in the same row"
)
return i
raise core.InconsistentTableError("No start line found for HTML data")
def end_line(self, lines):
"""
Return the line number at which table data ends.
"""
last_index = -1
for i, line in enumerate(lines):
if not isinstance(line, SoupString):
raise TypeError("HTML lines should be of type SoupString")
soup = line.soup
if soup.td is not None:
last_index = i
if last_index == -1:
return None
return last_index + 1
| HTMLData |
python | pytorch__pytorch | torch/_export/non_strict_utils.py | {
"start": 1859,
"end": 2000
} | class ____:
"""
Wraps `KeyPath` to aid `isinstance` checks.
"""
def __init__(self, kp: KeyPath):
self.kp = kp
| _KeyPath |
python | celery__celery | celery/bin/base.py | {
"start": 4079,
"end": 4646
} | class ____(click.Option):
"""Customized option for Celery."""
def get_default(self, ctx, *args, **kwargs):
if self.default_value_from_context:
self.default = ctx.obj[self.default_value_from_context]
return super().get_default(ctx, *args, **kwargs)
def __init__(self, *args, **kwargs):
"""Initialize a Celery option."""
self.help_group = kwargs.pop('help_group', None)
self.default_value_from_context = kwargs.pop('default_value_from_context', None)
super().__init__(*args, **kwargs)
| CeleryOption |
python | wandb__wandb | wandb/sdk/artifacts/_generated/fetch_registry.py | {
"start": 297,
"end": 443
} | class ____(GQLResult):
project: Optional[RegistryFragment]
FetchRegistry.model_rebuild()
FetchRegistryEntity.model_rebuild()
| FetchRegistryEntity |
python | fabric__fabric | tests/runners.py | {
"start": 627,
"end": 7664
} | class ____:
def needs_handle_on_a_Connection(self):
c = _Connection("host")
assert Remote(context=c).context is c
class env:
def replaces_when_replace_env_True(self, remote):
env = _runner().run(CMD, env={"JUST": "ME"}, replace_env=True).env
assert env == {"JUST": "ME"}
def augments_when_replace_env_False(self, remote):
env = _runner().run(CMD, env={"JUST": "ME"}, replace_env=False).env
assert (
"PATH" in env
) # assuming this will be in every test environment
assert "JUST" in env
assert env["JUST"] == "ME"
class run:
def calls_expected_paramiko_bits(self, remote):
# remote mocking makes generic safety checks like "were
# get_transport and open_session called", but we also want to make
# sure that exec_command got run with our arg to run().
remote.expect(cmd=CMD)
_runner().run(CMD)
def writes_remote_streams_to_local_streams(self, remote):
remote.expect(out=b"hello yes this is dog")
fakeout = StringIO()
_runner().run(CMD, out_stream=fakeout)
assert fakeout.getvalue() == "hello yes this is dog"
def return_value_is_Result_subclass_exposing_cxn_used(self, remote):
c = _Connection("host")
result = Remote(context=c).run(CMD)
assert isinstance(result, Result)
# Mild safety check for other Result superclass bits
assert result.ok is True
assert result.exited == 0
# Test the attr our own subclass adds
assert result.connection is c
def channel_is_closed_normally(self, remote):
chan = remote.expect()
# I.e. Remote.stop() closes the channel automatically
_runner().run(CMD)
chan.close.assert_called_once_with()
def channel_is_closed_on_body_exceptions(self, remote):
chan = remote.expect()
# I.e. Remote.stop() is called within a try/finally.
# Technically is just testing invoke.Runner, but meh.
class Oops(Exception):
pass
class _OopsRemote(Remote):
def wait(self):
raise Oops()
r = _OopsRemote(context=_Connection("host"))
try:
r.run(CMD)
except Oops:
chan.close.assert_called_once_with()
else:
assert False, "Runner failed to raise exception!"
def stop_calls_super_correctly(self, remote):
# RE: #2241
Runner.stop = Mock()
_runner().run(CMD)
Runner.stop.assert_called_once_with()
def channel_close_skipped_when_channel_not_even_made(self):
# I.e. if obtaining self.channel doesn't even happen (i.e. if
# Connection.create_session() dies), we need to account for that
# case...
class Oops(Exception):
pass
def oops():
raise Oops
cxn = _Connection("host")
cxn.create_session = oops
# When bug present, this will result in AttributeError because
# Remote has no 'channel'
try:
Remote(context=cxn).run(CMD)
except Oops:
pass
else:
assert False, "Weird, Oops never got raised..."
class pty_True:
def uses_paramiko_get_pty_with_local_size(self, remote):
chan = remote.expect()
_runner().run(CMD, pty=True)
cols, rows = pty_size()
chan.get_pty.assert_called_with(width=cols, height=rows)
@patch("fabric.runners.signal")
def no_SIGWINCH_means_no_handler(self, signal, remote):
delattr(signal, "SIGWINCH")
remote.expect()
_runner().run(CMD, pty=True)
assert not signal.signal.called
@patch("fabric.runners.signal")
def SIGWINCH_handled_when_present(self, signal, remote):
remote.expect()
runner = _runner()
runner.run(CMD, pty=True)
signal.signal.assert_has_calls(
[
# Setup
call(signal.SIGWINCH, runner.handle_window_change),
# Teardown
call(signal.SIGWINCH, signal.SIG_DFL),
]
)
@patch("fabric.runners.signal")
@patch("fabric.runners.threading")
def SIGWINCH_not_handled_in_subthreads(
self, threading, signal, remote
):
remote.expect()
threading.current_thread.return_value = "not main"
runner = _runner()
runner.run(CMD, pty=True)
assert not signal.signal.called
def window_change_handler_uses_resize_pty(self):
runner = _runner()
runner.channel = Mock()
runner.handle_window_change(None, None)
cols, rows = pty_size()
runner.channel.resize_pty.assert_called_once_with(cols, rows)
# TODO: how much of Invoke's tests re: the upper level run() (re:
# things like returning Result, behavior of Result, etc) to
# duplicate here? Ideally none or very few core ones.
# TODO: only test guts of our stuff, Invoke's Runner tests should
# handle all the normal shit like stdout/err print and capture.
# Implies we want a way to import & run those tests ourselves, though,
# with the Runner instead being a Remote. Or do we just replicate the
# basics?
# TODO: all other run() tests from fab1...
class start:
def sends_env_to_paramiko_update_environment_by_default(self, remote):
chan = remote.expect()
_runner().run(CMD, env={"FOO": "bar"})
chan.update_environment.assert_called_once_with({"FOO": "bar"})
def uses_export_prefixing_when_inline_env_is_True(self, remote):
chan = remote.expect(
cmd="export DEBUG=1 PATH=/opt/bin && {}".format(CMD)
)
r = Remote(context=_Connection("host"), inline_env=True)
r.run(CMD, env={"PATH": "/opt/bin", "DEBUG": "1"})
assert not chan.update_environment.called
def send_start_message_sends_exec_command(self):
runner = Remote(context=None)
runner.channel = Mock()
runner.send_start_message(command="whatever")
runner.channel.exec_command.assert_called_once_with("whatever")
def kill_closes_the_channel(self):
runner = _runner()
runner.channel = Mock()
runner.kill()
runner.channel.close.assert_called_once_with()
| Remote_ |
python | huggingface__transformers | src/transformers/models/unispeech_sat/modeling_unispeech_sat.py | {
"start": 29602,
"end": 38308
} | class ____(PreTrainedModel):
config: UniSpeechSatConfig
base_model_prefix = "unispeech_sat"
main_input_name = "input_values"
input_modalities = "audio"
supports_gradient_checkpointing = True
_supports_flash_attn = True
_supports_sdpa = True
_supports_flex_attn = True
@torch.no_grad()
def _init_weights(self, module):
"""Initialize the weights"""
# gumbel softmax requires special init
if isinstance(module, UniSpeechSatGumbelVectorQuantizer):
init.normal_(module.weight_proj.weight, mean=0.0, std=1)
init.zeros_(module.weight_proj.bias)
init.uniform_(module.codevectors)
elif isinstance(module, UniSpeechSatPositionalConvEmbedding):
init.normal_(
module.conv.weight,
mean=0,
std=2 * math.sqrt(1 / (module.conv.kernel_size[0] * module.conv.in_channels)),
)
init.constant_(module.conv.bias, 0)
elif isinstance(module, UniSpeechSatFeatureProjection):
k = math.sqrt(1 / module.projection.in_features)
init.uniform_(module.projection.weight, a=-k, b=k)
init.uniform_(module.projection.bias, a=-k, b=k)
elif isinstance(module, nn.Linear):
init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
if module.bias is not None:
init.zeros_(module.bias)
elif isinstance(module, (nn.LayerNorm, nn.GroupNorm)):
init.zeros_(module.bias)
init.ones_(module.weight)
elif isinstance(module, nn.Conv1d):
init.kaiming_normal_(module.weight)
if module.bias is not None:
k = math.sqrt(module.groups / (module.in_channels * module.kernel_size[0]))
init.uniform_(module.bias, a=-k, b=k)
def _get_feat_extract_output_lengths(self, input_lengths: Union[torch.LongTensor, int]):
"""
Computes the output length of the convolutional layers
"""
def _conv_out_length(input_length, kernel_size, stride):
# 1D convolutional layer output length formula taken
# from https://pytorch.org/docs/stable/generated/torch.nn.Conv1d.html
return torch.div(input_length - kernel_size, stride, rounding_mode="floor") + 1
for kernel_size, stride in zip(self.config.conv_kernel, self.config.conv_stride):
input_lengths = _conv_out_length(input_lengths, kernel_size, stride)
return input_lengths
def _get_feature_vector_attention_mask(self, feature_vector_length: int, attention_mask: torch.LongTensor):
# Effectively attention_mask.sum(-1), but not inplace to be able to run
# on inference mode.
non_padded_lengths = attention_mask.cumsum(dim=-1)[:, -1]
output_lengths = self._get_feat_extract_output_lengths(non_padded_lengths).to(torch.long)
batch_size = attention_mask.shape[0]
attention_mask = torch.zeros(
(batch_size, feature_vector_length), dtype=attention_mask.dtype, device=attention_mask.device
)
# these two operations makes sure that all values before the output lengths idxs are attended to
attention_mask[(torch.arange(attention_mask.shape[0], device=attention_mask.device), output_lengths - 1)] = 1
attention_mask = attention_mask.flip([-1]).cumsum(-1).flip([-1]).bool()
return attention_mask
def _compute_mask_indices(
shape: tuple[int, int],
mask_prob: float,
mask_length: int,
attention_mask: Optional[torch.LongTensor] = None,
min_masks: int = 0,
) -> np.ndarray:
"""
Computes random mask spans for a given shape. Used to implement [SpecAugment: A Simple Data Augmentation Method for
ASR](https://huggingface.co/papers/1904.08779). Note that this method is not optimized to run on TPU and should be run on
CPU as part of the preprocessing during training.
Args:
shape: The shape for which to compute masks. This should be of a tuple of size 2 where
the first element is the batch size and the second element is the length of the axis to span.
mask_prob: The percentage of the whole axis (between 0 and 1) which will be masked. The number of
independently generated mask spans of length `mask_length` is computed by
`mask_prob*shape[1]/mask_length`. Note that due to overlaps, `mask_prob` is an upper bound and the
actual percentage will be smaller.
mask_length: size of the mask
min_masks: minimum number of masked spans
attention_mask: A (right-padded) attention mask which independently shortens the feature axis of
each batch dimension.
"""
batch_size, sequence_length = shape
if mask_length < 1:
raise ValueError("`mask_length` has to be bigger than 0.")
if mask_length > sequence_length:
raise ValueError(
f"`mask_length` has to be smaller than `sequence_length`, but got `mask_length`: {mask_length}"
f" and `sequence_length`: {sequence_length}`"
)
# epsilon is used for probabilistic rounding
epsilon = np.random.rand(1).item()
def compute_num_masked_span(input_length):
"""Given input length, compute how many spans should be masked"""
num_masked_span = int(mask_prob * input_length / mask_length + epsilon)
num_masked_span = max(num_masked_span, min_masks)
# make sure num masked span <= sequence_length
if num_masked_span * mask_length > sequence_length:
num_masked_span = sequence_length // mask_length
# make sure num_masked span is also <= input_length - (mask_length - 1)
if input_length - (mask_length - 1) < num_masked_span:
num_masked_span = max(input_length - (mask_length - 1), 0)
return num_masked_span
# compute number of masked spans in batch
input_lengths = (
attention_mask.detach().sum(-1).tolist()
if attention_mask is not None
else [sequence_length for _ in range(batch_size)]
)
# SpecAugment mask to fill
spec_aug_mask = np.zeros((batch_size, sequence_length), dtype=bool)
spec_aug_mask_idxs = []
max_num_masked_span = compute_num_masked_span(sequence_length)
if max_num_masked_span == 0:
return spec_aug_mask
for input_length in input_lengths:
# compute num of masked spans for this input
num_masked_span = compute_num_masked_span(input_length)
# get random indices to mask
spec_aug_mask_idx = np.random.choice(
np.arange(input_length - (mask_length - 1)), num_masked_span, replace=False
)
# pick first sampled index that will serve as a dummy index to pad vector
# to ensure same dimension for all batches due to probabilistic rounding
# Picking first sample just pads those vectors twice.
if len(spec_aug_mask_idx) == 0:
# this case can only happen if `input_length` is strictly smaller then
# `sequence_length` in which case the last token has to be a padding
# token which we can use as a dummy mask id
dummy_mask_idx = sequence_length - 1
else:
dummy_mask_idx = spec_aug_mask_idx[0]
spec_aug_mask_idx = np.concatenate(
[spec_aug_mask_idx, np.ones(max_num_masked_span - num_masked_span, dtype=np.int32) * dummy_mask_idx]
)
spec_aug_mask_idxs.append(spec_aug_mask_idx)
spec_aug_mask_idxs = np.array(spec_aug_mask_idxs)
# expand masked indices to masked spans
spec_aug_mask_idxs = np.broadcast_to(
spec_aug_mask_idxs[:, :, None], (batch_size, max_num_masked_span, mask_length)
)
spec_aug_mask_idxs = spec_aug_mask_idxs.reshape(batch_size, max_num_masked_span * mask_length)
# add offset to the starting indexes so that indexes now create a span
offsets = np.arange(mask_length)[None, None, :]
offsets = np.broadcast_to(offsets, (batch_size, max_num_masked_span, mask_length)).reshape(
batch_size, max_num_masked_span * mask_length
)
spec_aug_mask_idxs = spec_aug_mask_idxs + offsets
# ensure that we cannot have indices larger than sequence_length
if spec_aug_mask_idxs.max() > sequence_length - 1:
spec_aug_mask_idxs[spec_aug_mask_idxs > sequence_length - 1] = sequence_length - 1
# scatter indices to mask
np.put_along_axis(spec_aug_mask, spec_aug_mask_idxs, 1, -1)
return spec_aug_mask
UniSpeechSatBaseModelOutput = Wav2Vec2BaseModelOutput
@auto_docstring
| UniSpeechSatPreTrainedModel |
python | pandas-dev__pandas | pandas/core/computation/expr.py | {
"start": 23893,
"end": 24112
} | class ____(BaseExprVisitor):
def __init__(
self, env, engine, parser, preparser=lambda source, f=None: source
) -> None:
super().__init__(env, engine, parser, preparser=preparser)
| PythonExprVisitor |
python | spack__spack | lib/spack/spack/database.py | {
"start": 19267,
"end": 71694
} | class ____:
#: Fields written for each install record
record_fields: Tuple[str, ...] = DEFAULT_INSTALL_RECORD_FIELDS
def __init__(
self,
root: str,
*,
upstream_dbs: Optional[List["Database"]] = None,
is_upstream: bool = False,
lock_cfg: LockConfiguration = DEFAULT_LOCK_CFG,
layout: Optional[DirectoryLayout] = None,
) -> None:
"""Database for Spack installations.
A Database is a cache of Specs data from ``$prefix/spec.yaml`` files
in Spack installation directories.
Database files (data and lock files) are stored under ``root/.spack-db``, which is
created if it does not exist. This is the "database directory".
The database will attempt to read an ``index.json`` file in the database directory.
If that does not exist, it will create a database when needed by scanning the entire
store root for ``spec.json`` files according to Spack's directory layout.
Args:
root: root directory where to create the database directory.
upstream_dbs: upstream databases for this repository.
is_upstream: whether this repository is an upstream.
lock_cfg: configuration for the locks to be used by this repository.
Relevant only if the repository is not an upstream.
"""
self.root = root
self.database_directory = pathlib.Path(self.root) / _DB_DIRNAME
self.layout = layout
# Set up layout of database files within the db dir
self._index_path = self.database_directory / INDEX_JSON_FILE
self._verifier_path = self.database_directory / _INDEX_VERIFIER_FILE
self._lock_path = self.database_directory / _LOCK_FILE
self.is_upstream = is_upstream
self.last_seen_verifier = ""
# Failed write transactions (interrupted by exceptions) will alert
# _write. When that happens, we set this flag to indicate that
# future read/write transactions should re-read the DB. Normally it
# would make more sense to resolve this at the end of the transaction
# but typically a failed transaction will terminate the running
# instance of Spack and we don't want to incur an extra read in that
# case, so we defer the cleanup to when we begin the next transaction
self._state_is_inconsistent = False
# initialize rest of state.
self.db_lock_timeout = lock_cfg.database_timeout
tty.debug(f"DATABASE LOCK TIMEOUT: {str(self.db_lock_timeout)}s")
self.lock: Union[ForbiddenLock, lk.Lock]
if self.is_upstream:
self.lock = ForbiddenLock()
else:
self.lock = lk.Lock(
str(self._lock_path),
default_timeout=self.db_lock_timeout,
desc="database",
enable=lock_cfg.enable,
)
self._data: Dict[str, InstallRecord] = {}
# For every installed spec we keep track of its install prefix, so that
# we can answer the simple query whether a given path is already taken
# before installing a different spec.
self._installed_prefixes: Set[str] = set()
self.upstream_dbs = list(upstream_dbs) if upstream_dbs else []
self._write_transaction_impl = lk.WriteTransaction
self._read_transaction_impl = lk.ReadTransaction
self._db_version: Optional[vn.ConcreteVersion] = None
@property
def db_version(self) -> vn.ConcreteVersion:
if self._db_version is None:
raise AttributeError("version not set -- DB has not been read yet")
return self._db_version
@db_version.setter
def db_version(self, value: vn.ConcreteVersion):
self._db_version = value
def _ensure_parent_directories(self):
"""Create the parent directory for the DB, if necessary."""
if not self.is_upstream:
self.database_directory.mkdir(parents=True, exist_ok=True)
def write_transaction(self):
"""Get a write lock context manager for use in a ``with`` block."""
return self._write_transaction_impl(self.lock, acquire=self._read, release=self._write)
def read_transaction(self):
"""Get a read lock context manager for use in a ``with`` block."""
return self._read_transaction_impl(self.lock, acquire=self._read)
def _write_to_file(self, stream):
"""Write out the database in JSON format to the stream passed
as argument.
This function does not do any locking or transactions.
"""
self._ensure_parent_directories()
# map from per-spec hash code to installation record.
installs = dict(
(k, v.to_dict(include_fields=self.record_fields)) for k, v in self._data.items()
)
# database includes installation list and version.
# NOTE: this DB version does not handle multiple installs of
# the same spec well. If there are 2 identical specs with
# different paths, it can't differentiate.
# TODO: fix this before we support multiple install locations.
database = {
"database": {
# TODO: move this to a top-level _meta section if we ever
# TODO: bump the DB version to 7
"version": str(_DB_VERSION),
# dictionary of installation records, keyed by DAG hash
"installs": installs,
}
}
try:
sjson.dump(database, stream)
except (TypeError, ValueError) as e:
raise sjson.SpackJSONError("error writing JSON database:", str(e))
def _read_spec_from_dict(self, spec_reader, hash_key, installs, hash=ht.dag_hash):
"""Recursively construct a spec from a hash in a YAML database.
Does not do any locking.
"""
spec_dict = installs[hash_key]["spec"]
# Install records don't include hash with spec, so we add it in here
# to ensure it is read properly.
if "name" not in spec_dict.keys():
# old format, can't update format here
for name in spec_dict:
spec_dict[name]["hash"] = hash_key
else:
# new format, already a singleton
spec_dict[hash.name] = hash_key
# Build spec from dict first.
return spec_reader.from_node_dict(spec_dict)
def db_for_spec_hash(self, hash_key):
with self.read_transaction():
if hash_key in self._data:
return self
for db in self.upstream_dbs:
if hash_key in db._data:
return db
def query_by_spec_hash(
self, hash_key: str, data: Optional[Dict[str, InstallRecord]] = None
) -> Tuple[bool, Optional[InstallRecord]]:
"""Get a spec for hash, and whether it's installed upstream.
Return:
Tuple of bool and optional InstallRecord. The bool tells us whether the record is from
an upstream. Its InstallRecord is also returned if available (the record must be
checked to know whether the hash is installed).
If the record is available locally, this function will always have
a preference for returning that, even if it is not installed locally
and is installed upstream.
"""
if data and hash_key in data:
return False, data[hash_key]
if not data:
with self.read_transaction():
if hash_key in self._data:
return False, self._data[hash_key]
for db in self.upstream_dbs:
if hash_key in db._data:
return True, db._data[hash_key]
return False, None
def query_local_by_spec_hash(self, hash_key: str) -> Optional[InstallRecord]:
"""Get a spec by hash in the local database
Return:
InstallRecord when installed locally, otherwise None."""
with self.read_transaction():
return self._data.get(hash_key, None)
def _assign_dependencies(
self,
spec_reader: Type["spack.spec.SpecfileReaderBase"],
hash_key: str,
installs: dict,
data: Dict[str, InstallRecord],
):
# Add dependencies from other records in the install DB to
# form a full spec.
spec = data[hash_key].spec
spec_node_dict = installs[hash_key]["spec"]
if "name" not in spec_node_dict:
# old format
spec_node_dict = spec_node_dict[spec.name]
if "dependencies" in spec_node_dict:
yaml_deps = spec_node_dict["dependencies"]
for dname, dhash, dtypes, _, virtuals, direct in spec_reader.read_specfile_dep_specs(
yaml_deps
):
# It is important that we always check upstream installations in the same order,
# and that we always check the local installation first: if a downstream Spack
# installs a package then dependents in that installation could be using it. If a
# hash is installed locally and upstream, there isn't enough information to
# determine which one a local package depends on, so the convention ensures that
# this isn't an issue.
_, record = self.query_by_spec_hash(dhash, data=data)
child = record.spec if record else None
if not child:
tty.warn(
f"Missing dependency not in database: "
f"{spec.cformat('{name}{/hash:7}')} needs {dname}-{dhash[:7]}"
)
continue
spec._add_dependency(
child, depflag=dt.canonicalize(dtypes), virtuals=virtuals, direct=direct
)
def _read_from_file(self, filename: pathlib.Path, *, reindex: bool = False) -> None:
"""Fill database from file, do not maintain old data.
Translate the spec portions from node-dict form to spec form.
Does not do any locking.
"""
try:
# In the future we may use a stream of JSON objects, hence `raw_decode` for compat.
fdata, _ = JSONDecoder().raw_decode(filename.read_text(encoding="utf-8"))
except Exception as e:
raise CorruptDatabaseError(f"error parsing database at {filename}:", str(e)) from e
if fdata is None:
return
def check(cond, msg):
if not cond:
raise CorruptDatabaseError(
f"Spack database is corrupt: {msg}", str(self._index_path)
)
check("database" in fdata, "no 'database' attribute in JSON DB.")
# High-level file checks
db = fdata["database"]
check("version" in db, "no 'version' in JSON DB.")
self.db_version = vn.StandardVersion.from_string(db["version"])
if self.db_version > _DB_VERSION:
raise InvalidDatabaseVersionError(self, _DB_VERSION, self.db_version)
elif self.db_version < _DB_VERSION:
installs = self._handle_old_db_versions_read(check, db, reindex=reindex)
else:
installs = self._handle_current_version_read(check, db)
spec_reader = reader(self.db_version)
def invalid_record(hash_key, error):
return CorruptDatabaseError(
f"Invalid record in Spack database: hash: {hash_key}, cause: "
f"{type(error).__name__}: {error}",
str(self._index_path),
)
# Build up the database in three passes:
#
# 1. Read in all specs without dependencies.
# 2. Hook dependencies up among specs.
# 3. Mark all specs concrete.
#
# The database is built up so that ALL specs in it share nodes
# (i.e., its specs are a true Merkle DAG, unlike most specs.)
# Pass 1: Iterate through database and build specs w/o dependencies
data: Dict[str, InstallRecord] = {}
installed_prefixes: Set[str] = set()
for hash_key, rec in installs.items():
try:
# This constructs a spec DAG from the list of all installs
spec = self._read_spec_from_dict(spec_reader, hash_key, installs)
# Insert the brand new spec in the database. Each
# spec has its own copies of its dependency specs.
# TODO: would a more immmutable spec implementation simplify
# this?
data[hash_key] = InstallRecord.from_dict(spec, rec)
if not spec.external and "installed" in rec and rec["installed"]:
installed_prefixes.add(rec["path"])
except Exception as e:
raise invalid_record(hash_key, e) from e
# Pass 2: Assign dependencies once all specs are created.
for hash_key in data:
try:
self._assign_dependencies(spec_reader, hash_key, installs, data)
except MissingDependenciesError:
raise
except Exception as e:
raise invalid_record(hash_key, e) from e
# Pass 3: Mark all specs concrete. Specs representing real
# installations must be explicitly marked.
# We do this *after* all dependencies are connected because if we
# do it *while* we're constructing specs,it causes hashes to be
# cached prematurely.
for hash_key, rec in data.items():
rec.spec._mark_root_concrete()
self._data = data
self._installed_prefixes = installed_prefixes
def _handle_current_version_read(self, check, db):
check("installs" in db, "no 'installs' in JSON DB.")
installs = db["installs"]
return installs
def _handle_old_db_versions_read(self, check, db, *, reindex: bool):
if reindex is False and not self.is_upstream:
self.raise_explicit_database_upgrade_error()
if not self.is_readable():
raise DatabaseNotReadableError(
f"cannot read database v{self.db_version} at {self.root}"
)
return self._handle_current_version_read(check, db)
def is_readable(self) -> bool:
"""Returns true if this DB can be read without reindexing"""
return (self.db_version, _DB_VERSION) in _REINDEX_NOT_NEEDED_ON_READ
def raise_explicit_database_upgrade_error(self):
"""Raises an ExplicitDatabaseUpgradeError with an appropriate message"""
raise ExplicitDatabaseUpgradeError(
f"database is v{self.db_version}, but Spack v{spack.__version__} needs v{_DB_VERSION}",
long_message=(
f"You will need to either:"
f"\n"
f"\n 1. Migrate the database to v{_DB_VERSION}, or"
f"\n 2. Use a new database by changing config:install_tree:root."
f"\n"
f"\nTo migrate the database at {self.root} "
f"\nto version {_DB_VERSION}, run:"
f"\n"
f"\n spack reindex"
f"\n"
f"\nNOTE that if you do this, older Spack versions will no longer"
f"\nbe able to read the database. However, `spack reindex` will create a backup,"
f"\nin case you want to revert."
f"\n"
f"\nIf you still need your old database, you can instead run"
f"\n`spack config edit config` and set install_tree:root to a new location."
),
)
def reindex(self):
"""Build database index from scratch based on a directory layout.
Locks the DB if it isn't locked already.
"""
if self.is_upstream:
raise UpstreamDatabaseLockingError("Cannot reindex an upstream database")
self._ensure_parent_directories()
# Special transaction to avoid recursive reindex calls and to
# ignore errors if we need to rebuild a corrupt database.
def _read_suppress_error():
try:
if self._index_path.is_file():
self._read_from_file(self._index_path, reindex=True)
except (CorruptDatabaseError, DatabaseNotReadableError):
self._data = {}
self._installed_prefixes = set()
with lk.WriteTransaction(self.lock, acquire=_read_suppress_error, release=self._write):
old_installed_prefixes, self._installed_prefixes = self._installed_prefixes, set()
old_data, self._data = self._data, {}
try:
self._reindex(old_data)
except BaseException:
# If anything explodes, restore old data, skip write.
self._data = old_data
self._installed_prefixes = old_installed_prefixes
raise
def _reindex(self, old_data: Dict[str, InstallRecord]):
# Specs on the file system are the source of truth for record.spec. The old database values
# if available are the source of truth for the rest of the record.
assert self.layout, "Database layout must be set to reindex"
specs_from_fs = self.layout.all_specs()
deprecated_for = self.layout.deprecated_for(specs_from_fs)
known_specs: List[spack.spec.Spec] = [
*specs_from_fs,
*(deprecated for _, deprecated in deprecated_for),
*(rec.spec for rec in old_data.values()),
]
upstream_hashes = {
dag_hash for upstream in self.upstream_dbs for dag_hash in upstream._data
}
upstream_hashes.difference_update(spec.dag_hash() for spec in known_specs)
def create_node(edge: spack.spec.DependencySpec, is_upstream: bool):
if is_upstream:
return
self._data[edge.spec.dag_hash()] = InstallRecord(
spec=edge.spec.copy(deps=False),
path=edge.spec.external_path if edge.spec.external else None,
installed=edge.spec.external,
)
# Store all nodes of known specs, excluding ones found in upstreams
tr.traverse_breadth_first_with_visitor(
known_specs,
tr.CoverNodesVisitor(
NoUpstreamVisitor(upstream_hashes, create_node), key=tr.by_dag_hash
),
)
# Store the prefix and other information for specs were found on the file system
for s in specs_from_fs:
record = self._data[s.dag_hash()]
record.path = s.prefix
record.installed = True
record.explicit = True # conservative assumption
record.installation_time = os.stat(s.prefix).st_ctime
# Deprecate specs
for new, old in deprecated_for:
self._data[old.dag_hash()].deprecated_for = new.dag_hash()
# Copy data we have from the old database
for old_record in old_data.values():
record = self._data[old_record.spec.dag_hash()]
record.explicit = old_record.explicit
record.installation_time = old_record.installation_time
record.origin = old_record.origin
record.deprecated_for = old_record.deprecated_for
# Warn when the spec has been removed from the file system (i.e. it was not detected)
if not record.installed and old_record.installed:
tty.warn(
f"Spec {old_record.spec.short_spec} was marked installed in the database "
"but was not found on the file system. It is now marked as missing."
)
def create_edge(edge: spack.spec.DependencySpec, is_upstream: bool):
if not edge.parent:
return
parent_record = self._data[edge.parent.dag_hash()]
if is_upstream:
upstream, child_record = self.query_by_spec_hash(edge.spec.dag_hash())
assert upstream and child_record, "Internal error: upstream spec not found"
else:
child_record = self._data[edge.spec.dag_hash()]
parent_record.spec._add_dependency(
child_record.spec, depflag=edge.depflag, virtuals=edge.virtuals
)
# Then store edges
tr.traverse_breadth_first_with_visitor(
known_specs,
tr.CoverEdgesVisitor(
NoUpstreamVisitor(upstream_hashes, create_edge), key=tr.by_dag_hash
),
)
# Finally update the ref counts
for record in self._data.values():
for dep in record.spec.dependencies(deptype=_TRACKED_DEPENDENCIES):
dep_record = self._data.get(dep.dag_hash())
if dep_record: # dep might be upstream
dep_record.ref_count += 1
if record.deprecated_for:
self._data[record.deprecated_for].ref_count += 1
self._check_ref_counts()
def _check_ref_counts(self):
"""Ensure consistency of reference counts in the DB.
Raise an AssertionError if something is amiss.
Does no locking.
"""
counts: Dict[str, int] = {}
for key, rec in self._data.items():
counts.setdefault(key, 0)
for dep in rec.spec.dependencies(deptype=_TRACKED_DEPENDENCIES):
dep_key = dep.dag_hash()
counts.setdefault(dep_key, 0)
counts[dep_key] += 1
if rec.deprecated_for:
counts.setdefault(rec.deprecated_for, 0)
counts[rec.deprecated_for] += 1
for rec in self._data.values():
key = rec.spec.dag_hash()
expected = counts[key]
found = rec.ref_count
if not expected == found:
raise AssertionError(
"Invalid ref_count: %s: %d (expected %d), in DB %s"
% (key, found, expected, self._index_path)
)
def _write(self, type=None, value=None, traceback=None):
"""Write the in-memory database index to its file path.
This is a helper function called by the WriteTransaction context
manager. If there is an exception while the write lock is active,
nothing will be written to the database file, but the in-memory
database *may* be left in an inconsistent state. It will be consistent
after the start of the next transaction, when it read from disk again.
This routine does no locking.
"""
self._ensure_parent_directories()
# Do not write if exceptions were raised
if type is not None:
# A failure interrupted a transaction, so we should record that
# the Database is now in an inconsistent state: we should
# restore it in the next transaction
self._state_is_inconsistent = True
return
temp_file = str(self._index_path) + (".%s.%s.temp" % (_gethostname(), os.getpid()))
# Write a temporary database file them move it into place
try:
with open(temp_file, "w", encoding="utf-8") as f:
self._write_to_file(f)
fs.rename(temp_file, str(self._index_path))
if _use_uuid:
with self._verifier_path.open("w", encoding="utf-8") as f:
new_verifier = str(uuid.uuid4())
f.write(new_verifier)
self.last_seen_verifier = new_verifier
except BaseException as e:
tty.debug(e)
# Clean up temp file if something goes wrong.
if os.path.exists(temp_file):
os.remove(temp_file)
raise
def _read(self):
"""Re-read Database from the data in the set location. This does no locking."""
if self._index_path.is_file():
current_verifier = ""
if _use_uuid:
try:
with self._verifier_path.open("r", encoding="utf-8") as f:
current_verifier = f.read()
except BaseException:
pass
if (current_verifier != self.last_seen_verifier) or (current_verifier == ""):
self.last_seen_verifier = current_verifier
# Read from file if a database exists
self._read_from_file(self._index_path)
elif self._state_is_inconsistent:
self._read_from_file(self._index_path)
self._state_is_inconsistent = False
return
elif self.is_upstream:
tty.warn(f"upstream not found: {self._index_path}")
def _add(
self,
spec: "spack.spec.Spec",
explicit: bool = False,
installation_time: Optional[float] = None,
allow_missing: bool = False,
):
"""Add an install record for this spec to the database.
Also ensures dependencies are present and updated in the DB as either installed or missing.
Args:
spec: spec to be added
explicit:
Possible values: True, False, any
A spec that was installed following a specific user request is marked as explicit.
If instead it was pulled-in as a dependency of a user requested spec it's
considered implicit.
installation_time:
Date and time of installation
allow_missing: if True, don't warn when installation is not found on on disk
This is useful when installing specs without build/test deps.
"""
if not spec.concrete:
raise NonConcreteSpecAddError("Specs added to DB must be concrete.")
key = spec.dag_hash()
spec_pkg_hash = spec._package_hash # type: ignore[attr-defined]
upstream, record = self.query_by_spec_hash(key)
if upstream and record and record.installed:
return
installation_time = installation_time or _now()
for edge in spec.edges_to_dependencies(depflag=_TRACKED_DEPENDENCIES):
if edge.spec.dag_hash() in self._data:
continue
self._add(
edge.spec,
explicit=False,
installation_time=installation_time,
# allow missing build / test only deps
allow_missing=allow_missing or edge.depflag & (dt.BUILD | dt.TEST) == edge.depflag,
)
# Make sure the directory layout agrees whether the spec is installed
if not spec.external and self.layout:
path = self.layout.path_for_spec(spec)
installed = False
try:
self.layout.ensure_installed(spec)
installed = True
self._installed_prefixes.add(path)
except DirectoryLayoutError as e:
if not (allow_missing and isinstance(e, InconsistentInstallDirectoryError)):
action = "updated" if key in self._data else "registered"
tty.warn(
f"{spec.short_spec} is being {action} in the database with prefix {path}, "
"but this directory does not contain an installation of "
f"the spec, due to: {e}"
)
elif spec.external_path:
path = spec.external_path
installed = True
else:
path = None
installed = True
if key not in self._data:
# Create a new install record with no deps initially.
new_spec = spec.copy(deps=False)
self._data[key] = InstallRecord(
new_spec,
path=path,
installed=installed,
ref_count=0,
explicit=explicit,
installation_time=installation_time,
origin=None if not hasattr(spec, "origin") else spec.origin,
)
# Connect dependencies from the DB to the new copy.
for dep in spec.edges_to_dependencies(depflag=_TRACKED_DEPENDENCIES):
dkey = dep.spec.dag_hash()
upstream, record = self.query_by_spec_hash(dkey)
assert record, f"Missing dependency {dep.spec.short_spec} in DB"
new_spec._add_dependency(record.spec, depflag=dep.depflag, virtuals=dep.virtuals)
if not upstream:
record.ref_count += 1
# Mark concrete once everything is built, and preserve the original hashes of concrete
# specs.
new_spec._mark_concrete()
new_spec._hash = key
new_spec._package_hash = spec_pkg_hash
else:
# It is already in the database
self._data[key].installed = installed
self._data[key].installation_time = _now()
self._data[key].explicit = explicit
@_autospec
def add(self, spec: "spack.spec.Spec", *, explicit: bool = False, allow_missing=False) -> None:
"""Add spec at path to database, locking and reading DB to sync.
``add()`` will lock and read from the DB on disk.
"""
# TODO: ensure that spec is concrete?
# Entire add is transactional.
with self.write_transaction():
self._add(spec, explicit=explicit, allow_missing=allow_missing)
def _get_matching_spec_key(self, spec: "spack.spec.Spec", **kwargs) -> str:
"""Get the exact spec OR get a single spec that matches."""
key = spec.dag_hash()
_, record = self.query_by_spec_hash(key)
if not record:
match = self.query_one(spec, **kwargs)
if match:
return match.dag_hash()
raise NoSuchSpecError(spec)
return key
@_autospec
def get_record(self, spec: "spack.spec.Spec", **kwargs) -> Optional[InstallRecord]:
key = self._get_matching_spec_key(spec, **kwargs)
_, record = self.query_by_spec_hash(key)
return record
def _decrement_ref_count(self, spec: "spack.spec.Spec") -> None:
key = spec.dag_hash()
if key not in self._data:
# TODO: print something here? DB is corrupt, but
# not much we can do.
return
rec = self._data[key]
rec.ref_count -= 1
if rec.ref_count == 0 and not rec.installed:
del self._data[key]
for dep in spec.dependencies(deptype=_TRACKED_DEPENDENCIES):
self._decrement_ref_count(dep)
def _increment_ref_count(self, spec: "spack.spec.Spec") -> None:
key = spec.dag_hash()
if key not in self._data:
return
rec = self._data[key]
rec.ref_count += 1
def _remove(self, spec: "spack.spec.Spec") -> "spack.spec.Spec":
"""Non-locking version of remove(); does real work."""
key = self._get_matching_spec_key(spec)
rec = self._data[key]
# This install prefix is now free for other specs to use, even if the
# spec is only marked uninstalled.
if not rec.spec.external and rec.installed and rec.path:
self._installed_prefixes.remove(rec.path)
if rec.ref_count > 0:
rec.installed = False
return rec.spec
del self._data[key]
# Remove any reference to this node from dependencies and
# decrement the reference count
rec.spec.detach(deptype=_TRACKED_DEPENDENCIES)
for dep in rec.spec.dependencies(deptype=_TRACKED_DEPENDENCIES):
self._decrement_ref_count(dep)
if rec.deprecated_for:
new_spec = self._data[rec.deprecated_for].spec
self._decrement_ref_count(new_spec)
# Returns the concrete spec so we know it in the case where a
# query spec was passed in.
return rec.spec
@_autospec
def remove(self, spec: "spack.spec.Spec") -> "spack.spec.Spec":
"""Removes a spec from the database. To be called on uninstall.
Reads the database, then:
1. Marks the spec as not installed.
2. Removes the spec if it has no more dependents.
3. If removed, recursively updates dependencies' ref counts
and removes them if they are no longer needed.
"""
# Take a lock around the entire removal.
with self.write_transaction():
return self._remove(spec)
def deprecator(self, spec: "spack.spec.Spec") -> Optional["spack.spec.Spec"]:
"""Return the spec that the given spec is deprecated for, or None"""
with self.read_transaction():
spec_key = self._get_matching_spec_key(spec)
spec_rec = self._data[spec_key]
if spec_rec.deprecated_for:
return self._data[spec_rec.deprecated_for].spec
else:
return None
def specs_deprecated_by(self, spec: "spack.spec.Spec") -> List["spack.spec.Spec"]:
"""Return all specs deprecated in favor of the given spec"""
with self.read_transaction():
return [
rec.spec for rec in self._data.values() if rec.deprecated_for == spec.dag_hash()
]
def _deprecate(self, spec: "spack.spec.Spec", deprecator: "spack.spec.Spec") -> None:
spec_key = self._get_matching_spec_key(spec)
spec_rec = self._data[spec_key]
deprecator_key = self._get_matching_spec_key(deprecator)
self._increment_ref_count(deprecator)
# If spec was already deprecated, update old deprecator's ref count
if spec_rec.deprecated_for:
old_repl_rec = self._data[spec_rec.deprecated_for]
self._decrement_ref_count(old_repl_rec.spec)
spec_rec.deprecated_for = deprecator_key
spec_rec.installed = False
self._data[spec_key] = spec_rec
@_autospec
def mark(self, spec: "spack.spec.Spec", key: str, value: Any) -> None:
"""Mark an arbitrary record on a spec."""
with self.write_transaction():
return self._mark(spec, key, value)
def _mark(self, spec: "spack.spec.Spec", key, value) -> None:
record = self._data[self._get_matching_spec_key(spec)]
setattr(record, key, value)
@_autospec
def deprecate(self, spec: "spack.spec.Spec", deprecator: "spack.spec.Spec") -> None:
"""Marks a spec as deprecated in favor of its deprecator"""
with self.write_transaction():
return self._deprecate(spec, deprecator)
@_autospec
def installed_relatives(
self,
spec: "spack.spec.Spec",
direction: tr.DirectionType = "children",
transitive: bool = True,
deptype: Union[dt.DepFlag, dt.DepTypes] = dt.ALL,
) -> Set["spack.spec.Spec"]:
"""Return installed specs related to this one."""
if direction not in ("parents", "children"):
raise ValueError("Invalid direction: %s" % direction)
relatives: Set[spack.spec.Spec] = set()
for spec in self.query(spec):
if transitive:
to_add = spec.traverse(direction=direction, root=False, deptype=deptype)
elif direction == "parents":
to_add = spec.dependents(deptype=deptype)
else: # direction == 'children'
to_add = spec.dependencies(deptype=deptype)
for relative in to_add:
hash_key = relative.dag_hash()
_, record = self.query_by_spec_hash(hash_key)
if not record:
tty.warn(
f"Inconsistent state: "
f"{'dependent' if direction == 'parents' else 'dependency'} {hash_key} of "
f"{spec.dag_hash()} not in DB"
)
continue
if not record.installed:
continue
relatives.add(relative)
return relatives
@_autospec
def installed_extensions_for(self, extendee_spec: "spack.spec.Spec"):
"""Returns the specs of all packages that extend the given spec"""
for spec in self.query():
if spec.package.extends(extendee_spec):
yield spec.package
def _get_by_hash_local(
self,
dag_hash: str,
default: Optional[List["spack.spec.Spec"]] = None,
installed: Union[bool, InstallRecordStatus] = InstallRecordStatus.ANY,
) -> Optional[List["spack.spec.Spec"]]:
installed = normalize_query(installed)
# hash is a full hash and is in the data somewhere
if dag_hash in self._data:
rec = self._data[dag_hash]
if rec.install_type_matches(installed):
return [rec.spec]
else:
return default
# check if hash is a prefix of some installed (or previously installed) spec.
matches = [
record.spec
for h, record in self._data.items()
if h.startswith(dag_hash) and record.install_type_matches(installed)
]
if matches:
return matches
# nothing found
return default
def get_by_hash_local(
self,
dag_hash: str,
default: Optional[List["spack.spec.Spec"]] = None,
installed: Union[bool, InstallRecordStatus] = InstallRecordStatus.ANY,
) -> Optional[List["spack.spec.Spec"]]:
"""Look up a spec in *this DB* by DAG hash, or by a DAG hash prefix.
Args:
dag_hash: hash (or hash prefix) to look up
default: default value to return if dag_hash is not in the DB
installed: if ``True``, includes only installed specs in the search; if ``False``
only missing specs. Otherwise, a InstallRecordStatus flag.
``installed`` defaults to ``InstallRecordStatus.ANY`` so we can refer to any known hash.
``query()`` and ``query_one()`` differ in that they only return installed specs by default.
"""
with self.read_transaction():
return self._get_by_hash_local(dag_hash, default=default, installed=installed)
def get_by_hash(
self,
dag_hash: str,
default: Optional[List["spack.spec.Spec"]] = None,
installed: Union[bool, InstallRecordStatus] = InstallRecordStatus.ANY,
) -> Optional[List["spack.spec.Spec"]]:
"""Look up a spec by DAG hash, or by a DAG hash prefix.
Args:
dag_hash: hash (or hash prefix) to look up
default: default value to return if dag_hash is not in the DB
installed: if ``True``, includes only installed specs in the search; if ``False``
only missing specs. Otherwise, a InstallRecordStatus flag.
``installed`` defaults to ``InstallRecordStatus.ANY`` so we can refer to any known hash.
``query()`` and ``query_one()`` differ in that they only return installed specs by default.
"""
spec = self.get_by_hash_local(dag_hash, default=default, installed=installed)
if spec is not None:
return spec
for upstream_db in self.upstream_dbs:
spec = upstream_db._get_by_hash_local(dag_hash, default=default, installed=installed)
if spec is not None:
return spec
return default
def _query(
self,
query_spec: Optional[Union[str, "spack.spec.Spec"]] = None,
*,
predicate_fn: Optional[SelectType] = None,
installed: Union[bool, InstallRecordStatus] = True,
explicit: Optional[bool] = None,
start_date: Optional[datetime.datetime] = None,
end_date: Optional[datetime.datetime] = None,
hashes: Optional[Iterable[str]] = None,
in_buildcache: Optional[bool] = None,
origin: Optional[str] = None,
) -> List["spack.spec.Spec"]:
installed = normalize_query(installed)
# Restrict the set of records over which we iterate first
matching_hashes = self._data
if hashes is not None:
matching_hashes = {h: self._data[h] for h in hashes if h in self._data}
if isinstance(query_spec, str):
query_spec = spack.spec.Spec(query_spec)
if query_spec is not None and query_spec.concrete:
hash_key = query_spec.dag_hash()
if hash_key not in matching_hashes:
return []
matching_hashes = {hash_key: matching_hashes[hash_key]}
results = []
start_date = start_date or datetime.datetime.min
end_date = end_date or datetime.datetime.max
deferred = []
for rec in matching_hashes.values():
if origin and not (origin == rec.origin):
continue
if not rec.install_type_matches(installed):
continue
if in_buildcache is not None and rec.in_buildcache != in_buildcache:
continue
if explicit is not None and rec.explicit != explicit:
continue
if predicate_fn is not None and not predicate_fn(rec):
continue
if start_date or end_date:
inst_date = datetime.datetime.fromtimestamp(rec.installation_time)
if not (start_date < inst_date < end_date):
continue
if query_spec is None or query_spec.concrete:
results.append(rec.spec)
continue
# check anon specs and exact name matches first
if not query_spec.name or rec.spec.name == query_spec.name:
if rec.spec.satisfies(query_spec):
results.append(rec.spec)
# save potential virtual matches for later, but not if we already found a match
elif not results:
deferred.append(rec.spec)
# Checking for virtuals is expensive, so we save it for last and only if needed.
# If we get here, we didn't find anything in the DB that matched by name.
# If we did fine something, the query spec can't be virtual b/c we matched an actual
# package installation, so skip the virtual check entirely. If we *didn't* find anything,
# check all the deferred specs *if* the query is virtual.
if (
not results
and query_spec is not None
and deferred
and spack.repo.PATH.is_virtual(query_spec.name)
):
results = [spec for spec in deferred if spec.satisfies(query_spec)]
return results
def query_local(
self,
query_spec: Optional[Union[str, "spack.spec.Spec"]] = None,
*,
predicate_fn: Optional[SelectType] = None,
installed: Union[bool, InstallRecordStatus] = True,
explicit: Optional[bool] = None,
start_date: Optional[datetime.datetime] = None,
end_date: Optional[datetime.datetime] = None,
hashes: Optional[List[str]] = None,
in_buildcache: Optional[bool] = None,
origin: Optional[str] = None,
) -> List["spack.spec.Spec"]:
"""Queries the local Spack database.
This function doesn't guarantee any sorting of the returned data for performance reason,
since comparing specs for __lt__ may be an expensive operation.
Args:
query_spec: if query_spec is ``None``, match all specs in the database.
If it is a spec, return all specs matching ``spec.satisfies(query_spec)``.
predicate_fn: optional predicate taking an InstallRecord as argument, and returning
whether that record is selected for the query. It can be used to craft criteria
that need some data for selection not provided by the Database itself.
installed: if ``True``, includes only installed specs in the search. If ``False`` only
missing specs, and if ``any``, all specs in database. If an InstallStatus or
iterable of InstallStatus, returns specs whose install status matches at least
one of the InstallStatus.
explicit: a spec that was installed following a specific user request is marked as
explicit. If instead it was pulled-in as a dependency of a user requested spec
it's considered implicit.
start_date: if set considers only specs installed from the starting date.
end_date: if set considers only specs installed until the ending date.
in_buildcache: specs that are marked in this database as part of an associated binary
cache are ``in_buildcache``. All other specs are not. This field is used for
querying mirror indices. By default, it does not check this status.
hashes: list of hashes used to restrict the search
origin: origin of the spec
"""
with self.read_transaction():
return self._query(
query_spec,
predicate_fn=predicate_fn,
installed=installed,
explicit=explicit,
start_date=start_date,
end_date=end_date,
hashes=hashes,
in_buildcache=in_buildcache,
origin=origin,
)
def query(
self,
query_spec: Optional[Union[str, "spack.spec.Spec"]] = None,
*,
predicate_fn: Optional[SelectType] = None,
installed: Union[bool, InstallRecordStatus] = True,
explicit: Optional[bool] = None,
start_date: Optional[datetime.datetime] = None,
end_date: Optional[datetime.datetime] = None,
in_buildcache: Optional[bool] = None,
hashes: Optional[List[str]] = None,
origin: Optional[str] = None,
install_tree: str = "all",
) -> List["spack.spec.Spec"]:
"""Queries the Spack database including all upstream databases.
Args:
query_spec: if query_spec is ``None``, match all specs in the database.
If it is a spec, return all specs matching ``spec.satisfies(query_spec)``.
predicate_fn: optional predicate taking an InstallRecord as argument, and returning
whether that record is selected for the query. It can be used to craft criteria
that need some data for selection not provided by the Database itself.
installed: if ``True``, includes only installed specs in the search. If ``False`` only
missing specs, and if ``any``, all specs in database. If an InstallStatus or
iterable of InstallStatus, returns specs whose install status matches at least
one of the InstallStatus.
explicit: a spec that was installed following a specific user request is marked as
explicit. If instead it was pulled-in as a dependency of a user requested spec
it's considered implicit.
start_date: if set considers only specs installed from the starting date.
end_date: if set considers only specs installed until the ending date.
in_buildcache: specs that are marked in this database as part of an associated binary
cache are ``in_buildcache``. All other specs are not. This field is used for
querying mirror indices. By default, it does not check this status.
hashes: list of hashes used to restrict the search
install_tree: query ``"all"`` (default), ``"local"``, ``"upstream"``, or upstream path
origin: origin of the spec
"""
valid_trees = ["all", "upstream", "local", self.root] + [u.root for u in self.upstream_dbs]
if install_tree not in valid_trees:
msg = "Invalid install_tree argument to Database.query()\n"
msg += f"Try one of {', '.join(valid_trees)}"
tty.error(msg)
return []
upstream_results = []
upstreams = self.upstream_dbs
if install_tree not in ("all", "upstream"):
upstreams = [u for u in self.upstream_dbs if u.root == install_tree]
for upstream_db in upstreams:
# queries for upstream DBs need to *not* lock - we may not
# have permissions to do this and the upstream DBs won't know about
# us anyway (so e.g. they should never uninstall specs)
upstream_results.extend(
upstream_db._query(
query_spec,
predicate_fn=predicate_fn,
installed=installed,
explicit=explicit,
start_date=start_date,
end_date=end_date,
hashes=hashes,
in_buildcache=in_buildcache,
origin=origin,
)
or []
)
local_results: Set["spack.spec.Spec"] = set()
if install_tree in ("all", "local") or self.root == install_tree:
local_results = set(
self.query_local(
query_spec,
predicate_fn=predicate_fn,
installed=installed,
explicit=explicit,
start_date=start_date,
end_date=end_date,
hashes=hashes,
in_buildcache=in_buildcache,
origin=origin,
)
)
results = list(local_results) + list(x for x in upstream_results if x not in local_results)
results.sort() # type: ignore[call-arg,call-overload]
return results
def query_one(
self,
query_spec: Optional[Union[str, "spack.spec.Spec"]],
predicate_fn: Optional[SelectType] = None,
installed: Union[bool, InstallRecordStatus] = True,
) -> Optional["spack.spec.Spec"]:
"""Query for exactly one spec that matches the query spec.
Returns None if no installed package matches.
Raises:
AssertionError: if more than one spec matches the query.
"""
concrete_specs = self.query(query_spec, predicate_fn=predicate_fn, installed=installed)
assert len(concrete_specs) <= 1
return concrete_specs[0] if concrete_specs else None
def missing(self, spec):
key = spec.dag_hash()
_, record = self.query_by_spec_hash(key)
return record and not record.installed
def is_occupied_install_prefix(self, path):
with self.read_transaction():
return path in self._installed_prefixes
def all_hashes(self):
"""Return dag hash of every spec in the database."""
with self.read_transaction():
return list(self._data.keys())
def unused_specs(
self,
root_hashes: Optional[Container[str]] = None,
deptype: Union[dt.DepFlag, dt.DepTypes] = dt.LINK | dt.RUN,
) -> List["spack.spec.Spec"]:
"""Return all specs that are currently installed but not needed by root specs.
By default, roots are all explicit specs in the database. If a set of root
hashes are passed in, they are instead used as the roots.
Arguments:
root_hashes: optional list of roots to consider when evaluating needed installations.
deptype: if a spec is reachable from a root via these dependency types, it is
considered needed. By default only link and run dependency types are considered.
"""
def root(key, record):
"""Whether a DB record is a root for garbage collection."""
return key in root_hashes if root_hashes is not None else record.explicit
with self.read_transaction():
roots = [rec.spec for key, rec in self._data.items() if root(key, rec)]
needed = set(id(spec) for spec in tr.traverse_nodes(roots, deptype=deptype))
return [
rec.spec
for rec in self._data.values()
if id(rec.spec) not in needed and rec.installed
]
| Database |
python | huggingface__transformers | src/transformers/models/funnel/tokenization_funnel.py | {
"start": 1185,
"end": 7144
} | class ____(TokenizersBackend):
r"""
Construct a Funnel Transformer tokenizer (backed by HuggingFace's tokenizers library). Based on WordPiece.
This tokenizer inherits from [`TokenizersBackend`] which contains most of the main methods. Users should
refer to this superclass for more information regarding those methods.
Args:
vocab_file (`str`):
File containing the vocabulary.
do_lower_case (`bool`, *optional*, defaults to `True`):
Whether or not to lowercase the input when tokenizing.
unk_token (`str`, *optional*, defaults to `"<unk>"`):
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
token instead.
sep_token (`str`, *optional*, defaults to `"<sep>"`):
The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
sequence classification or for a text and a question for question answering. It is also used as the last
token of a sequence built with special tokens.
pad_token (`str`, *optional*, defaults to `"<pad>"`):
The token used for padding, for example when batching sequences of different lengths.
cls_token (`str`, *optional*, defaults to `"<cls>"`):
The classifier token which is used when doing sequence classification (classification of the whole sequence
instead of per-token classification). It is the first token of the sequence when built with special tokens.
mask_token (`str`, *optional*, defaults to `"<mask>"`):
The token used for masking values. This is the token used when training this model with masked language
modeling. This is the token which the model will try to predict.
clean_text (`bool`, *optional*, defaults to `True`):
Whether or not to clean the text before tokenization by removing any control characters and replacing all
whitespaces by the classic one.
tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
Whether or not to tokenize Chinese characters. This should likely be deactivated for Japanese (see [this
issue](https://github.com/huggingface/transformers/issues/328)).
bos_token (`str`, `optional`, defaults to `"<s>"`):
The beginning of sentence token.
eos_token (`str`, `optional`, defaults to `"</s>"`):
The end of sentence token.
strip_accents (`bool`, *optional*):
Whether or not to strip all accents. If this option is not specified, then it will be determined by the
value for `lowercase` (as in the original BERT).
wordpieces_prefix (`str`, *optional*, defaults to `"##"`):
The prefix for subwords.
vocab (`dict`, *optional*):
Custom vocabulary dictionary.
"""
vocab_files_names = VOCAB_FILES_NAMES
slow_tokenizer_class = None
cls_token_type_id: int = 2
def __init__(
self,
do_lower_case: bool = True,
unk_token: str = "<unk>",
sep_token: str = "<sep>",
pad_token: str = "<pad>",
cls_token: str = "<cls>",
mask_token: str = "<mask>",
bos_token: str = "<s>",
eos_token: str = "</s>",
clean_text: bool = True,
tokenize_chinese_chars: bool = True,
strip_accents: Optional[bool] = None,
wordpieces_prefix: str = "##",
vocab: Optional[dict] = None,
vocab_file: Optional[str] = None,
**kwargs,
):
self.vocab_file = vocab_file
self.do_lower_case = do_lower_case
self.tokenize_chinese_chars = tokenize_chinese_chars
self.strip_accents = strip_accents
self.clean_text = clean_text
self.wordpieces_prefix = wordpieces_prefix
if vocab is not None:
self._vocab = (
{token: idx for idx, (token, _score) in enumerate(vocab)} if isinstance(vocab, list) else vocab
)
else:
self._vocab = {
str(pad_token): 0,
str(unk_token): 1,
str(cls_token): 2,
str(sep_token): 3,
str(mask_token): 4,
str(bos_token): 5,
str(eos_token): 6,
}
self._tokenizer = Tokenizer(WordPiece(self._vocab, unk_token=str(unk_token)))
self._tokenizer.normalizer = normalizers.BertNormalizer(
clean_text=clean_text,
handle_chinese_chars=tokenize_chinese_chars,
strip_accents=strip_accents,
lowercase=do_lower_case,
)
self._tokenizer.pre_tokenizer = pre_tokenizers.BertPreTokenizer()
self._tokenizer.decoder = decoders.WordPiece(prefix=wordpieces_prefix)
self._tokenizer.post_processor = processors.TemplateProcessing(
single=f"{cls_token}:2 $A:0 {sep_token}:0", # token_type_id is 2 for Funnel transformer
pair=f"{cls_token}:2 $A:0 {sep_token}:0 $B:1 {sep_token}:1",
special_tokens=[
(str(cls_token), self._vocab.get(str(cls_token), 2)),
(str(sep_token), self._vocab.get(str(sep_token), 3)),
],
)
tokenizer_object = self._tokenizer
super().__init__(
tokenizer_object=tokenizer_object,
do_lower_case=do_lower_case,
unk_token=unk_token,
sep_token=sep_token,
pad_token=pad_token,
cls_token=cls_token,
mask_token=mask_token,
bos_token=bos_token,
eos_token=eos_token,
clean_text=clean_text,
tokenize_chinese_chars=tokenize_chinese_chars,
strip_accents=strip_accents,
wordpieces_prefix=wordpieces_prefix,
**kwargs,
)
__all__ = ["FunnelTokenizer"]
| FunnelTokenizer |
python | getsentry__sentry | tests/sentry/utils/test_retries.py | {
"start": 144,
"end": 1562
} | class ____(TestCase):
bomb = Exception("Boom!")
def test_policy_success(self) -> None:
callable = mock.MagicMock(side_effect=[self.bomb, mock.sentinel.OK])
always_retry = lambda i, e: True
assert ConditionalRetryPolicy(always_retry)(callable) is mock.sentinel.OK
assert callable.call_count == 2
def test_poilcy_failure(self) -> None:
callable = mock.MagicMock(side_effect=self.bomb)
never_retry = lambda i, e: False
with pytest.raises(Exception) as e:
ConditionalRetryPolicy(never_retry)(callable)
assert callable.call_count == 1
assert e.value is self.bomb
def test_policy_counter(self) -> None:
callable = mock.MagicMock(side_effect=self.bomb)
retry_once = lambda i, e: i < 2
with pytest.raises(Exception) as e:
ConditionalRetryPolicy(retry_once)(callable)
assert callable.call_count == 2
assert e.value is self.bomb
def test_policy_exception_filtering(self) -> None:
errors = [Exception(), Exception(), Exception()]
callable = mock.MagicMock(side_effect=errors)
sometimes_retry = lambda i, e: e is not errors[-1]
with pytest.raises(Exception) as e:
ConditionalRetryPolicy(sometimes_retry)(callable)
assert e.value is errors[-1]
assert callable.call_count == 3
| ConditionalRetryPolicyTestCase |
python | apache__airflow | providers/microsoft/azure/tests/unit/microsoft/azure/hooks/test_data_lake.py | {
"start": 7809,
"end": 14966
} | class ____:
def setup_class(self) -> None:
self.conn_id: str = "adls_conn_id1"
self.file_system_name = "test_file_system"
self.directory_name = "test_directory"
self.file_name = "test_file_name"
@mock.patch(f"{MODULE}.AzureDataLakeStorageV2Hook.get_conn")
def test_create_file_system(self, mock_conn):
hook = AzureDataLakeStorageV2Hook(adls_conn_id=self.conn_id)
hook.create_file_system("test_file_system")
expected_calls = [mock.call().create_file_system(file_system=self.file_system_name)]
mock_conn.assert_has_calls(expected_calls)
@mock.patch(f"{MODULE}.FileSystemClient")
@mock.patch(f"{MODULE}.AzureDataLakeStorageV2Hook.get_conn")
def test_get_file_system(self, mock_conn, mock_file_system):
mock_conn.return_value.get_file_system_client.return_value = mock_file_system
hook = AzureDataLakeStorageV2Hook(adls_conn_id=self.conn_id)
result = hook.get_file_system(self.file_system_name)
assert result == mock_file_system
@mock.patch(f"{MODULE}.DataLakeDirectoryClient")
@mock.patch(f"{MODULE}.AzureDataLakeStorageV2Hook.get_file_system")
@mock.patch(f"{MODULE}.AzureDataLakeStorageV2Hook.get_conn")
def test_create_directory(self, mock_conn, mock_get_file_system, mock_directory_client):
mock_get_file_system.return_value.create_directory.return_value = mock_directory_client
hook = AzureDataLakeStorageV2Hook(adls_conn_id=self.conn_id)
result = hook.create_directory(self.file_system_name, self.directory_name)
assert result == mock_directory_client
@mock.patch(f"{MODULE}.DataLakeDirectoryClient")
@mock.patch(f"{MODULE}.AzureDataLakeStorageV2Hook.get_file_system")
@mock.patch(f"{MODULE}.AzureDataLakeStorageV2Hook.get_conn")
def test_get_directory(self, mock_conn, mock_get_file_system, mock_directory_client):
mock_get_file_system.return_value.get_directory_client.return_value = mock_directory_client
hook = AzureDataLakeStorageV2Hook(adls_conn_id=self.conn_id)
result = hook.get_directory_client(self.file_system_name, self.directory_name)
assert result == mock_directory_client
@mock.patch(f"{MODULE}.DataLakeFileClient")
@mock.patch(f"{MODULE}.AzureDataLakeStorageV2Hook.get_file_system")
@mock.patch(f"{MODULE}.AzureDataLakeStorageV2Hook.get_conn")
def test_create_file(self, mock_conn, mock_get_file_system, mock_file_client):
mock_get_file_system.return_value.create_file.return_value = mock_file_client
hook = AzureDataLakeStorageV2Hook(adls_conn_id=self.conn_id)
result = hook.create_file(self.file_system_name, self.file_name)
assert result == mock_file_client
@mock.patch(f"{MODULE}.AzureDataLakeStorageV2Hook.get_conn")
def test_delete_file_system(self, mock_conn):
hook = AzureDataLakeStorageV2Hook(adls_conn_id=self.conn_id)
hook.delete_file_system(self.file_system_name)
expected_calls = [mock.call().delete_file_system(self.file_system_name)]
mock_conn.assert_has_calls(expected_calls)
@mock.patch(f"{MODULE}.DataLakeDirectoryClient")
@mock.patch(f"{MODULE}.AzureDataLakeStorageV2Hook.get_conn")
def test_delete_directory(self, mock_conn, mock_directory_client):
mock_conn.return_value.get_directory_client.return_value = mock_directory_client
hook = AzureDataLakeStorageV2Hook(adls_conn_id=self.conn_id)
hook.delete_directory(self.file_system_name, self.directory_name)
expected_calls = [
mock.call()
.get_file_system_client(self.file_system_name)
.get_directory_client(self.directory_name)
.delete_directory()
]
mock_conn.assert_has_calls(expected_calls)
@mock.patch(f"{MODULE}.AzureDataLakeStorageV2Hook.get_conn")
def test_list_file_system(self, mock_conn):
hook = AzureDataLakeStorageV2Hook(adls_conn_id=self.conn_id)
hook.list_file_system(prefix="prefix")
mock_conn.return_value.list_file_systems.assert_called_once_with(
name_starts_with="prefix", include_metadata=False
)
@mock.patch(f"{MODULE}.AzureDataLakeStorageV2Hook.get_file_system")
@mock.patch(f"{MODULE}.AzureDataLakeStorageV2Hook.get_conn")
def test_list_files_directory(self, mock_conn, mock_get_file_system):
hook = AzureDataLakeStorageV2Hook(adls_conn_id=self.conn_id)
hook.list_files_directory(self.file_system_name, self.directory_name)
mock_get_file_system.return_value.get_paths.assert_called_once_with(self.directory_name)
@pytest.mark.parametrize(
argnames="list_file_systems_result",
argvalues=[iter([FileSystemProperties]), iter([])],
)
@mock.patch(f"{MODULE}.AzureDataLakeStorageV2Hook.get_conn")
def test_connection_success(self, mock_conn, list_file_systems_result):
hook = AzureDataLakeStorageV2Hook(adls_conn_id=self.conn_id)
hook.get_conn().list_file_systems.return_value = list_file_systems_result
status, msg = hook.test_connection()
assert status is True
assert msg == "Successfully connected to ADLS Gen2 Storage."
@mock.patch(f"{MODULE}.AzureDataLakeStorageV2Hook.get_conn")
def test_connection_failure(self, mock_conn):
hook = AzureDataLakeStorageV2Hook(adls_conn_id=self.conn_id)
hook.get_conn().list_file_systems = PropertyMock(side_effect=Exception("Authentication failed."))
status, msg = hook.test_connection()
assert status is False
assert msg == "Authentication failed."
@mock.patch(f"{MODULE}.AzureDataLakeStorageV2Hook.get_connection")
def test_proxies_passed_to_credentials(self, mock_conn):
hook = AzureDataLakeStorageV2Hook(adls_conn_id=self.conn_id)
mock_conn.return_value = Connection(
conn_id=self.conn_id,
login="client_id",
password="secret",
extra={
"tenant_id": "tenant-id",
"proxies": {"https": "https://proxy:80"},
"account_url": "https://onelake.dfs.fabric.microsoft.com",
},
)
conn: DataLakeServiceClient = hook.get_conn()
assert conn is not None
assert conn.primary_endpoint == "https://onelake.dfs.fabric.microsoft.com/"
assert conn.primary_hostname == "onelake.dfs.fabric.microsoft.com"
assert conn.scheme == "https"
assert conn.url == "https://onelake.dfs.fabric.microsoft.com/"
assert conn.credential._client_id == "client_id"
assert conn.credential._client_credential == "secret"
assert self.find_policy(conn, ProxyPolicy) is not None
assert self.find_policy(conn, ProxyPolicy).proxies["https"] == "https://proxy:80"
def find_policy(self, conn, policy_type):
policies = conn.credential._client._pipeline._impl_policies
return next(
map(
lambda policy: policy._policy,
filter(lambda policy: isinstance(policy._policy, policy_type), policies),
)
)
| TestAzureDataLakeStorageV2Hook |
python | getsentry__sentry | tests/snuba/incidents/test_tasks.py | {
"start": 1176,
"end": 8129
} | class ____(TestCase):
def setUp(self) -> None:
super().setUp()
self.topic = Topic.METRICS_SUBSCRIPTIONS_RESULTS
self.orig_registry = deepcopy(subscriber_registry)
cluster_options = kafka_config.get_kafka_admin_cluster_options(
"default", {"allow.auto.create.topics": "true"}
)
self.admin_client = AdminClient(cluster_options)
topic_defn = kafka_config.get_topic_definition(self.topic)
self.real_topic = topic_defn["real_topic_name"]
self.cluster = topic_defn["cluster"]
create_topics(self.cluster, [self.real_topic])
def tearDown(self) -> None:
super().tearDown()
subscriber_registry.clear()
subscriber_registry.update(self.orig_registry)
self.admin_client.delete_topics([self.real_topic])
metrics._metrics_backend = None
@cached_property
def snuba_query(self) -> SnubaQuery:
return SnubaQuery.objects.create(
type=SnubaQuery.Type.ERROR.value,
dataset="events",
aggregate="count()",
query="",
time_window=60,
resolution=60,
environment=None,
)
@cached_property
def subscription(self) -> QuerySubscription:
return QuerySubscription.objects.create(
status=QuerySubscription.Status.ACTIVE.value,
project=self.project,
snuba_query=self.snuba_query,
type=INCIDENTS_SNUBA_SUBSCRIPTION_TYPE,
subscription_id="8/fake_subscription_id",
)
@cached_property
def detector(self) -> Detector:
from sentry.incidents.grouptype import MetricIssue
# Create condition group for detector thresholds
condition_group = self.create_data_condition_group()
detector = self.create_detector(
name="Test Metric Alert Detector",
project=self.project,
type=MetricIssue.slug,
workflow_condition_group=condition_group,
created_by_id=self.user.id,
config={
"detection_type": "static", # Required for MetricIssue detectors
"comparison_delta": None,
},
)
# Create DetectorState to track detector state
self.create_detector_state(detector=detector)
# Create data conditions for the detector (critical and resolve thresholds)
# Critical: >= 100 triggers HIGH priority (matching AlertRule ABOVE semantics)
self.create_data_condition(
type=Condition.GREATER_OR_EQUAL,
comparison=100,
condition_result=DetectorPriorityLevel.HIGH,
condition_group=condition_group,
)
# Resolve: <= 10 triggers OK state
self.create_data_condition(
type=Condition.LESS_OR_EQUAL,
comparison=10,
condition_result=DetectorPriorityLevel.OK,
condition_group=condition_group,
)
data_source = self.create_data_source(
organization=self.organization,
type=DATA_SOURCE_SNUBA_QUERY_SUBSCRIPTION,
source_id=str(self.subscription.id),
)
self.create_data_source_detector(data_source=data_source, detector=detector)
return detector
@cached_property
def producer(self) -> Producer:
conf = {
"bootstrap.servers": settings.KAFKA_CLUSTERS[self.cluster]["common"][
"bootstrap.servers"
],
"session.timeout.ms": 6000,
}
return Producer(conf)
def run_test(self, consumer: StreamProcessor) -> None:
# Full integration test to ensure that when a subscription receives an update
# the `QuerySubscriptionConsumer` successfully retries the subscription and
# calls the correct callback, which should result in a GroupOpenPeriod being created.
# Ensure detector is initialized before test runs
_ = self.detector
message = {
"version": 3,
"payload": {
"subscription_id": self.subscription.subscription_id,
"result": {
"data": [{"some_col": 101}],
"meta": [{"name": "count", "type": "UInt64"}],
},
"request": {
"some": "data",
"query": """MATCH (metrics_counters) SELECT sum(value) AS value BY
tags[3] WHERE org_id = 1 AND project_id IN tuple(1) AND metric_id = 16
AND tags[3] IN tuple(13, 4)""",
},
"entity": "metrics_counters",
"timestamp": "2020-01-01T01:23:45.1234",
},
}
self.producer.produce(self.real_topic, json.dumps(message))
self.producer.flush()
original_callback = subscriber_registry[INCIDENTS_SNUBA_SUBSCRIPTION_TYPE]
callback_invoked = []
def shutdown_callback(*args, **kwargs):
# We want to just exit after the callback so that we can see the result of
# processing.
callback_invoked.append(True)
original_callback(*args, **kwargs)
consumer.signal_shutdown()
subscriber_registry[INCIDENTS_SNUBA_SUBSCRIPTION_TYPE] = shutdown_callback
with self.feature("organizations:incidents"):
with self.tasks(), self.capture_on_commit_callbacks(execute=True):
# Integration test: verify Kafka consumer successfully processes
# subscription updates through the workflow engine without error.
consumer.run()
# Verify the callback was invoked
assert callback_invoked, "Subscription processor callback should have been invoked"
# Verify workflow engine evaluated the detector correctly
detector_state = DetectorState.objects.filter(detector=self.detector).first()
assert detector_state is not None
assert detector_state.is_triggered
# Note: This test verifies subscription processing through the workflow engine.
# IssueOccurrences are created but not persisted to Groups in this test since
# that would require the occurrence consumer to be running, which is outside
# the scope of this Kafka subscription consumer integration test.
def test_arroyo(self) -> None:
from sentry.consumers import get_stream_processor
consumer = get_stream_processor(
"metrics-subscription-results",
consumer_args=["--max-batch-size=1", "--max-batch-time-ms=1000", "--processes=1"],
topic=None,
cluster=None,
group_id="hi",
strict_offset_reset=True,
auto_offset_reset="earliest",
enforce_schema=True,
)
self.run_test(consumer)
| HandleSnubaQueryUpdateTest |
python | PyCQA__pylint | tests/functional/t/too/too_many_positional_arguments.py | {
"start": 71,
"end": 443
} | class ____:
"""The max positional arguments default is 5."""
def fail1(self, a, b, c, d, e): # [too-many-arguments, too-many-positional-arguments]
pass
def fail2(self, a, b, c, d, /, e): # [too-many-arguments, too-many-positional-arguments]
pass
def okay1(self, a, b, c, d, *, e=True): # [too-many-arguments]
pass
| FiveArgumentMethods |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/django/toystore/forms.py | {
"start": 1795,
"end": 1902
} | class ____(ReprModelForm):
class Meta:
model = OddFields
fields = "__all__"
| OddFieldsForm |
python | fastapi__sqlmodel | docs_src/tutorial/fastapi/teams/tutorial001.py | {
"start": 506,
"end": 606
} | class ____(SQLModel):
name: Optional[str] = None
headquarters: Optional[str] = None
| TeamUpdate |
python | fastapi__sqlmodel | docs_src/tutorial/fastapi/app_testing/tutorial001/main.py | {
"start": 305,
"end": 403
} | class ____(HeroBase, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
| Hero |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/assets/graph/remote_asset_graph.py | {
"start": 17587,
"end": 22146
} | class ____(BaseAssetGraph[TRemoteAssetNode], ABC, Generic[TRemoteAssetNode]):
@property
@abstractmethod
def remote_asset_nodes_by_key(self) -> Mapping[AssetKey, TRemoteAssetNode]: ...
@property
@abstractmethod
def remote_asset_check_nodes_by_key(
self,
) -> Mapping[AssetCheckKey, RemoteAssetCheckNode]: ...
# TODO this should just be what is returned from get()
def get_remote_asset_check_node(self, key: AssetCheckKey) -> RemoteAssetCheckNode:
return self.remote_asset_check_nodes_by_key[key]
def _get_asset_check_node_from_remote_asset_check_node(
self, remote_node: RemoteAssetCheckNode
) -> AssetCheckNode:
return AssetCheckNode(
remote_node.asset_check.key,
remote_node.asset_check.additional_asset_keys,
remote_node.asset_check.blocking,
remote_node.asset_check.description,
remote_node.asset_check.automation_condition,
{}, # metadata not yet on AssetCheckNodeSnap
)
##### COMMON ASSET GRAPH INTERFACE
@cached_property
def _asset_check_nodes_by_key(self) -> Mapping[AssetCheckKey, AssetCheckNode]: # pyright: ignore[reportIncompatibleVariableOverride]
return {
k: self._get_asset_check_node_from_remote_asset_check_node(v)
for k, v in self.remote_asset_check_nodes_by_key.items()
}
def get_execution_set_asset_and_check_keys( # pyright: ignore[reportIncompatibleMethodOverride]
self, entity_key: EntityKey
) -> AbstractSet[EntityKey]:
if isinstance(entity_key, AssetKey):
return self.get(entity_key).execution_set_entity_keys
else: # AssetCheckKey
return self.get_remote_asset_check_node(entity_key).execution_set_entity_keys
##### REMOTE-SPECIFIC METHODS
@property
def asset_checks(self) -> Sequence["AssetCheckNodeSnap"]:
return [node.asset_check for node in self.remote_asset_check_nodes_by_key.values()]
@cached_property
def _asset_check_nodes_by_asset_key(self) -> Mapping[AssetKey, Sequence[RemoteAssetCheckNode]]:
by_asset_key = {}
for node in self.remote_asset_check_nodes_by_key.values():
by_asset_key.setdefault(node.asset_check.asset_key, []).append(node)
return by_asset_key
def get_checks_for_asset(self, asset_key: AssetKey) -> Sequence[RemoteAssetCheckNode]:
return self._asset_check_nodes_by_asset_key.get(asset_key, [])
def get_check_keys_for_assets(
self, asset_keys: AbstractSet[AssetKey]
) -> AbstractSet[AssetCheckKey]:
return (
set().union(
*(
{check.asset_check.key for check in self.get_checks_for_asset(asset_key)}
for asset_key in asset_keys
)
)
if asset_keys
else set()
)
@cached_property
def asset_check_keys(self) -> AbstractSet[AssetCheckKey]: # pyright: ignore[reportIncompatibleMethodOverride]
return set(self.remote_asset_check_nodes_by_key.keys())
def asset_keys_for_job(self, job_name: str) -> AbstractSet[AssetKey]:
return {node.key for node in self.asset_nodes if job_name in node.job_names}
@cached_property
def all_job_names(self) -> AbstractSet[str]:
return {job_name for node in self.asset_nodes for job_name in node.job_names}
def get_materialization_job_names(self, asset_key: AssetKey) -> Sequence[str]:
"""Returns the names of jobs that materialize this asset."""
# This is a poorly named method because it will expose observation job names for assets with
# a defined observation but no materialization.
return self.get(asset_key).job_names
def get_materialization_asset_keys_for_job(self, job_name: str) -> Sequence[AssetKey]:
"""Returns asset keys that are targeted for materialization in the given job."""
return [
k
for k in self.materializable_asset_keys
if job_name in self.get_materialization_job_names(k)
]
def get_implicit_job_name_for_assets(
self,
asset_keys: Iterable[AssetKey],
remote_repo: Optional[RemoteRepository],
) -> Optional[str]:
"""Returns the name of the asset base job that contains all the given assets, or None if there is no such
job.
Note: all asset_keys should be in the same repository.
"""
return IMPLICIT_ASSET_JOB_NAME
@record
| RemoteAssetGraph |
python | kamyu104__LeetCode-Solutions | Python/android-unlock-patterns.py | {
"start": 59,
"end": 1827
} | class ____(object):
def numberOfPatterns(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
def merge(used, i):
return used | (1 << i)
def number_of_keys(i):
number = 0
while i > 0:
i &= i - 1
number += 1
return number
def contain(used, i):
return bool(used & (1 << i))
def convert(i, j):
return 3 * i + j
# dp[i][j]: i is the set of the numbers in binary representation,
# dp[i][j] is the number of ways ending with the number j.
dp = [[0] * 9 for _ in xrange(1 << 9)]
for i in xrange(9):
dp[merge(0, i)][i] = 1
res = 0
for used in xrange(len(dp)):
number = number_of_keys(used)
if number > n:
continue
for i in xrange(9):
if not contain(used, i):
continue
if m <= number <= n:
res += dp[used][i]
x1, y1 = divmod(i, 3)
for j in xrange(9):
if contain(used, j):
continue
x2, y2 = divmod(j, 3)
if ((x1 == x2 and abs(y1 - y2) == 2) or
(y1 == y2 and abs(x1 - x2) == 2) or
(abs(x1 - x2) == 2 and abs(y1 - y2) == 2)) and \
not contain(used,
convert((x1 + x2) // 2, (y1 + y2) // 2)):
continue
dp[merge(used, j)][j] += dp[used][i]
return res
# Time: O(9^2 * 2^9)
# Space: O(9 * 2^9)
# DP solution.
| Solution |
python | coleifer__peewee | tests/fields.py | {
"start": 3781,
"end": 4375
} | class ____(ModelTestCase):
requires = [DecimalModel]
def test_decimal_field(self):
d1 = DecimalModel.create(value=D('3'))
d2 = DecimalModel.create(value=D('100.33'))
self.assertEqual(sorted(d.value for d in DecimalModel.select()),
[D('3'), D('100.33')])
def test_decimal_rounding(self):
d = DecimalModel.create(value=D('1.2345'), value_up=D('1.2345'))
d_db = DecimalModel.get(DecimalModel.id == d.id)
self.assertEqual(d_db.value, D('1.23'))
self.assertEqual(d_db.value_up, D('1.24'))
| TestDecimalField |
python | kamyu104__LeetCode-Solutions | Python/word-pattern.py | {
"start": 1159,
"end": 1775
} | class ____(object):
def wordPattern(self, pattern, str):
"""
:type pattern: str
:type str: str
:rtype: bool
"""
words = str.split() # Space: O(n)
if len(pattern) != len(words):
return False
w2p, p2w = {}, {}
for p, w in izip(pattern, words):
if w not in w2p and p not in p2w:
# Build mapping. Space: O(c)
w2p[w] = p
p2w[p] = w
elif w not in w2p or w2p[w] != p:
# Contradict mapping.
return False
return True
| Solution2 |
python | lazyprogrammer__machine_learning_examples | rnn_class/batch_units.py | {
"start": 458,
"end": 1688
} | class ____:
def __init__(self, Mi, Mo, activation):
self.Mi = Mi
self.Mo = Mo
self.f = activation
# numpy init
Wxh = init_weight(Mi, Mo)
Whh = init_weight(Mo, Mo)
b = np.zeros(Mo)
h0 = np.zeros(Mo)
# theano vars
self.Wxh = theano.shared(Wxh)
self.Whh = theano.shared(Whh)
self.b = theano.shared(b)
self.h0 = theano.shared(h0)
self.params = [self.Wxh, self.Whh, self.b, self.h0]
def get_ht(self, xWxh_t, h_t1):
return self.f(xWxh_t + h_t1.dot(self.Whh) + self.b)
def recurrence(self, xWxh_t, is_start, h_t1, h0):
h_t = T.switch(
T.eq(is_start, 1),
self.get_ht(xWxh_t, h0),
self.get_ht(xWxh_t, h_t1)
)
return h_t
def output(self, Xflat, startPoints):
# Xflat should be (NT, D)
# calculate X after multiplying input weights
XWxh = Xflat.dot(self.Wxh)
h, _ = theano.scan(
fn=self.recurrence,
sequences=[XWxh, startPoints],
outputs_info=[self.h0],
non_sequences=[self.h0],
n_steps=Xflat.shape[0],
)
return h
| SimpleRecurrentLayer |
python | python-attrs__attrs | tests/test_converters.py | {
"start": 5873,
"end": 7570
} | class ____:
def test_success(self):
"""
Succeeds if all wrapped converters succeed.
"""
c = pipe(str, Converter(to_bool), bool)
assert (
True
is c.converter("True", None, None)
is c.converter(True, None, None)
)
def test_fail(self):
"""
Fails if any wrapped converter fails.
"""
c = pipe(str, to_bool)
# First wrapped converter fails:
with pytest.raises(ValueError):
c(33)
# Last wrapped converter fails:
with pytest.raises(ValueError):
c("33")
def test_sugar(self):
"""
`pipe(c1, c2, c3)` and `[c1, c2, c3]` are equivalent.
"""
@attr.s
class C:
a1 = attrib(default="True", converter=pipe(str, to_bool, bool))
a2 = attrib(default=True, converter=[str, to_bool, bool])
c = C()
assert True is c.a1 is c.a2
def test_empty(self):
"""
Empty pipe returns same value.
"""
o = object()
assert o is pipe()(o)
def test_wrapped_annotation(self):
"""
The return type of the wrapped converter is copied into its __call__
and ultimately into pipe's wrapped converter.
"""
def last(value) -> bool:
return bool(value)
@attr.s
class C:
x = attr.ib(converter=[Converter(int), Converter(last)])
i = C(5)
assert True is i.x
assert (
bool
is _AnnotationExtractor(
attr.fields(C).x.converter.__call__
).get_return_type()
)
| TestPipe |
python | sqlalchemy__sqlalchemy | test/dialect/mssql/test_types.py | {
"start": 47787,
"end": 51953
} | class ____(fixtures.TestBase):
__only_on__ = "mssql"
__requires__ = ("non_broken_binary",)
__backend__ = True
@testing.combinations(
(
mssql.MSVarBinary(800),
b("some normal data"),
None,
True,
None,
False,
),
(
mssql.VARBINARY("max"),
"binary_data_one.dat",
None,
False,
None,
False,
),
(
mssql.VARBINARY("max"),
"binary_data_one.dat",
None,
True,
None,
False,
),
(
mssql.VARBINARY(filestream=True),
"binary_data_one.dat",
None,
True,
None,
False,
testing.requires.mssql_filestream,
),
(
sqltypes.LargeBinary,
"binary_data_one.dat",
None,
False,
None,
False,
),
(sqltypes.LargeBinary, "binary_data_one.dat", None, True, None, False),
(mssql.MSImage, "binary_data_one.dat", None, True, None, False),
(PickleType, pickleable.Foo("im foo 1"), None, True, None, False),
(
MyPickleType,
pickleable.Foo("im foo 1"),
pickleable.Foo("im foo 1", stuff="BINDim stuffRESULT"),
True,
None,
False,
),
(types.BINARY(100), "binary_data_one.dat", None, True, 100, False),
(types.VARBINARY(100), "binary_data_one.dat", None, True, 100, False),
(mssql.VARBINARY(100), "binary_data_one.dat", None, True, 100, False),
(types.BINARY(100), "binary_data_two.dat", None, True, 99, True),
(types.VARBINARY(100), "binary_data_two.dat", None, True, 99, False),
(mssql.VARBINARY(100), "binary_data_two.dat", None, True, 99, False),
argnames="type_, data, expected, deprecate_large_types, "
"slice_, zeropad",
)
def test_round_trip(
self,
metadata,
type_,
data,
expected,
deprecate_large_types,
slice_,
zeropad,
):
if (
testing.db.dialect.deprecate_large_types
is not deprecate_large_types
):
engine = engines.testing_engine(
options={"deprecate_large_types": deprecate_large_types}
)
else:
engine = testing.db
binary_table = Table(
"binary_table",
metadata,
Column("id", Integer, primary_key=True),
Column("data", type_),
)
binary_table.create(engine)
if isinstance(data, str) and (
data == "binary_data_one.dat" or data == "binary_data_two.dat"
):
data = self._load_stream(data)
if slice_ is not None:
data = data[0:slice_]
if expected is None:
if zeropad:
expected = data[0:slice_] + b"\x00"
else:
expected = data
with engine.begin() as conn:
conn.execute(binary_table.insert(), dict(data=data))
eq_(conn.scalar(select(binary_table.c.data)), expected)
eq_(
conn.scalar(
text("select data from binary_table").columns(
binary_table.c.data
)
),
expected,
)
conn.execute(binary_table.delete())
conn.execute(binary_table.insert(), dict(data=None))
eq_(conn.scalar(select(binary_table.c.data)), None)
eq_(
conn.scalar(
text("select data from binary_table").columns(
binary_table.c.data
)
),
None,
)
def _load_stream(self, name, len_=3000):
fp = open(
os.path.join(os.path.dirname(__file__), "..", "..", name), "rb"
)
stream = fp.read(len_)
fp.close()
return stream
| BinaryTest |
python | kamyu104__LeetCode-Solutions | Python/divisor-game.py | {
"start": 650,
"end": 1234
} | class ____(object):
def divisorGame(self, n):
"""
:type n: int
:rtype: bool
"""
def factors(n):
result = [[] for _ in xrange(n+1)]
for i in xrange(1, n+1):
for j in range(i, n+1, i):
result[j].append(i)
return result
FACTORS = factors(n)
dp = [False]*(n+1)
for i in xrange(2, n+1):
dp[i] = any(not dp[i-j] for j in FACTORS[i] if j != i)
return dp[-1]
# Time: O(nlogn)
# Space: O(nlogn)
# memoization, number theory
| Solution2 |
python | donnemartin__system-design-primer | solutions/system_design/web_crawler/web_crawler_snippets.py | {
"start": 26,
"end": 868
} | class ____(object):
def __init__(self, db):
self.db = db
pass
def add_link_to_crawl(self, url):
"""Add the given link to `links_to_crawl`."""
pass
def remove_link_to_crawl(self, url):
"""Remove the given link from `links_to_crawl`."""
pass
def reduce_priority_link_to_crawl(self, url):
"""Reduce the priority of a link in `links_to_crawl` to avoid cycles."""
pass
def extract_max_priority_page(self):
"""Return the highest priority link in `links_to_crawl`."""
pass
def insert_crawled_link(self, url, signature):
"""Add the given link to `crawled_links`."""
pass
def crawled_similar(self, signature):
"""Determine if we've already crawled a page matching the given signature"""
pass
| PagesDataStore |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.