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
numba__numba
numba/core/typing/builtins.py
{ "start": 5881, "end": 5943 }
class ____(BinOp): pass @infer_global(operator.sub)
BinOpAdd
python
getsentry__sentry
src/sentry/models/files/file.py
{ "start": 531, "end": 1716 }
class ____(AbstractFile[FileBlobIndex, FileBlob]): blobs = models.ManyToManyField("sentry.FileBlob", through="sentry.FileBlobIndex") # <Legacy fields> # Remove in 8.1 blob = FlexibleForeignKey("sentry.FileBlob", null=True, related_name="legacy_blob") path = models.TextField(null=True) # </Legacy fields> class Meta: app_label = "sentry" db_table = "sentry_file" def _blob_index_records(self) -> Sequence[FileBlobIndex]: return sorted( FileBlobIndex.objects.filter(file=self).select_related("blob"), key=lambda fbi: fbi.offset, ) def _create_blob_index(self, blob: FileBlob, offset: int) -> FileBlobIndex: return FileBlobIndex.objects.create(file=self, blob=blob, offset=offset) def _create_blob_from_file(self, contents: ContentFile, logger: Any) -> FileBlob: return FileBlob.from_file(contents, logger) def _get_blobs_by_id(self, blob_ids: Sequence[int]) -> models.QuerySet[FileBlob]: return FileBlob.objects.filter(id__in=blob_ids).all() def _delete_unreferenced_blob_task(self) -> Task[Any, Any]: return delete_unreferenced_blobs_region
File
python
networkx__networkx
networkx/classes/tests/test_reportviews.py
{ "start": 189, "end": 1836 }
class ____: @classmethod def setup_class(cls): cls.G = nx.path_graph(9) cls.nv = cls.G.nodes # NodeView(G) def test_pickle(self): import pickle nv = self.nv pnv = pickle.loads(pickle.dumps(nv, -1)) assert nv == pnv assert nv.__slots__ == pnv.__slots__ def test_str(self): assert str(self.nv) == "[0, 1, 2, 3, 4, 5, 6, 7, 8]" def test_repr(self): assert repr(self.nv) == "NodeView((0, 1, 2, 3, 4, 5, 6, 7, 8))" def test_contains(self): G = self.G.copy() nv = G.nodes assert 7 in nv assert 9 not in nv G.remove_node(7) G.add_node(9) assert 7 not in nv assert 9 in nv def test_getitem(self): G = self.G.copy() nv = G.nodes G.nodes[3]["foo"] = "bar" assert nv[7] == {} assert nv[3] == {"foo": "bar"} # slicing with pytest.raises(nx.NetworkXError): G.nodes[0:5] def test_iter(self): nv = self.nv for i, n in enumerate(nv): assert i == n inv = iter(nv) assert next(inv) == 0 assert iter(nv) != nv assert iter(inv) == inv inv2 = iter(nv) next(inv2) assert list(inv) == list(inv2) # odd case where NodeView calls NodeDataView with data=False nnv = nv(data=False) for i, n in enumerate(nnv): assert i == n def test_call(self): nodes = self.nv assert nodes is nodes() assert nodes is not nodes(data=True) assert nodes is not nodes(data="weight")
TestNodeView
python
dask__distributed
distributed/shuffle/_core.py
{ "start": 15626, "end": 15950 }
class ____(Generic[_T_partition_id]): run_id: int = field(init=False, default_factory=partial(next, itertools.count(1))) spec: ShuffleSpec worker_for: dict[_T_partition_id, str] span_id: str | None @property def id(self) -> ShuffleId: return self.spec.id @dataclass(frozen=True)
ShuffleRunSpec
python
huggingface__transformers
src/transformers/models/cohere/modeling_cohere.py
{ "start": 10295, "end": 14200 }
class ____(nn.Module): """Multi-headed attention from 'Attention Is All You Need' paper""" def __init__(self, config: CohereConfig, layer_idx: Optional[int] = None): super().__init__() self.config = config self.layer_idx = layer_idx self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads) self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads self.scaling = self.head_dim**-0.5 self.attention_dropout = config.attention_dropout self.is_causal = True self.q_proj = nn.Linear( config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias ) self.k_proj = nn.Linear( config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias ) self.v_proj = nn.Linear( config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias ) self.o_proj = nn.Linear( config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias ) self.rotary_fn = apply_rotary_pos_emb self.use_qk_norm = config.use_qk_norm if self.use_qk_norm: # When sharding the model using Tensor Parallelism, need to be careful to use n_local_heads self.q_norm = CohereLayerNorm( hidden_size=(config.num_attention_heads, self.head_dim), eps=config.layer_norm_eps ) self.k_norm = CohereLayerNorm( hidden_size=(config.num_key_value_heads, self.head_dim), eps=config.layer_norm_eps ) def forward( self, hidden_states: torch.Tensor, position_embeddings: tuple[torch.Tensor, torch.Tensor], attention_mask: Optional[torch.Tensor], past_key_values: Optional[Cache] = None, cache_position: Optional[torch.LongTensor] = None, **kwargs: Unpack[FlashAttentionKwargs], ) -> tuple[torch.Tensor, Optional[torch.Tensor]]: input_shape = hidden_states.shape[:-1] hidden_shape = (*input_shape, -1, self.head_dim) query_states = self.q_proj(hidden_states).view(hidden_shape) key_states = self.k_proj(hidden_states).view(hidden_shape) value_states = self.v_proj(hidden_states).view(hidden_shape) if self.use_qk_norm: # main diff from Llama query_states = self.q_norm(query_states) key_states = self.k_norm(key_states) query_states = query_states.transpose(1, 2) key_states = key_states.transpose(1, 2) value_states = value_states.transpose(1, 2) cos, sin = position_embeddings query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin) if past_key_values is not None: # sin and cos are specific to RoPE models; position_ids needed for the static cache cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs) attention_interface: Callable = eager_attention_forward if self.config._attn_implementation != "eager": attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation] attn_output, attn_weights = attention_interface( self, query_states, key_states, value_states, attention_mask, dropout=0.0 if not self.training else self.attention_dropout, scaling=self.scaling, **kwargs, ) attn_output = attn_output.reshape(*input_shape, -1).contiguous() attn_output = self.o_proj(attn_output) return attn_output, attn_weights
CohereAttention
python
tensorflow__tensorflow
tensorflow/python/data/ops/map_op.py
{ "start": 4521, "end": 5953 }
class ____(dataset_ops.UnaryDataset): """A `Dataset` that maps a function over elements in its input.""" def __init__( self, input_dataset, map_func, force_synchronous=False, use_inter_op_parallelism=True, preserve_cardinality=True, use_legacy_function=False, name=None, ): self._input_dataset = input_dataset self._use_inter_op_parallelism = use_inter_op_parallelism self._preserve_cardinality = preserve_cardinality self._map_func = structured_function.StructuredFunctionWrapper( map_func, self._transformation_name(), dataset=input_dataset, use_legacy_function=use_legacy_function) self._force_synchronous = force_synchronous self._name = name variant_tensor = gen_dataset_ops.map_dataset( input_dataset._variant_tensor, # pylint: disable=protected-access self._map_func.function.captured_inputs, f=self._map_func.function, use_inter_op_parallelism=self._use_inter_op_parallelism, preserve_cardinality=self._preserve_cardinality, force_synchronous=self._force_synchronous, **self._common_args ) super().__init__(input_dataset, variant_tensor) def _functions(self): return [self._map_func] @property def element_spec(self): return self._map_func.output_structure def _transformation_name(self): return "Dataset.map()"
_MapDataset
python
pyinstaller__pyinstaller
bootloader/waflib/Tools/c_osx.py
{ "start": 4696, "end": 4875 }
class ____(Task.Task): color = 'PINK' def run(self): self.outputs[0].parent.mkdir() shutil.copy2(self.inputs[0].srcpath(), self.outputs[0].abspath())
macapp
python
spack__spack
lib/spack/spack/vendor/pyrsistent/_pclass.py
{ "start": 1301, "end": 8057 }
class ____(CheckedType, metaclass=PClassMeta): """ A PClass is a python class with a fixed set of specified fields. PClasses are declared as python classes inheriting from PClass. It is defined the same way that PRecords are and behaves like a PRecord in all aspects except that it is not a PMap and hence not a collection but rather a plain Python object. More documentation and examples of PClass usage is available at https://github.com/tobgu/spack.vendor.pyrsistent """ def __new__(cls, **kwargs): # Support *args? result = super(PClass, cls).__new__(cls) factory_fields = kwargs.pop('_factory_fields', None) ignore_extra = kwargs.pop('ignore_extra', None) missing_fields = [] invariant_errors = [] for name, field in cls._pclass_fields.items(): if name in kwargs: if factory_fields is None or name in factory_fields: if is_field_ignore_extra_complaint(PClass, field, ignore_extra): value = field.factory(kwargs[name], ignore_extra=ignore_extra) else: value = field.factory(kwargs[name]) else: value = kwargs[name] _check_and_set_attr(cls, field, name, value, result, invariant_errors) del kwargs[name] elif field.initial is not PFIELD_NO_INITIAL: initial = field.initial() if callable(field.initial) else field.initial _check_and_set_attr( cls, field, name, initial, result, invariant_errors) elif field.mandatory: missing_fields.append('{0}.{1}'.format(cls.__name__, name)) if invariant_errors or missing_fields: raise InvariantException(tuple(invariant_errors), tuple(missing_fields), 'Field invariant failed') if kwargs: raise AttributeError("'{0}' are not among the specified fields for {1}".format( ', '.join(kwargs), cls.__name__)) check_global_invariants(result, cls._pclass_invariants) result._pclass_frozen = True return result def set(self, *args, **kwargs): """ Set a field in the instance. Returns a new instance with the updated value. The original instance remains unmodified. Accepts key-value pairs or single string representing the field name and a value. >>> from spack.vendor.pyrsistent import PClass, field >>> class AClass(PClass): ... x = field() ... >>> a = AClass(x=1) >>> a2 = a.set(x=2) >>> a3 = a.set('x', 3) >>> a AClass(x=1) >>> a2 AClass(x=2) >>> a3 AClass(x=3) """ if args: kwargs[args[0]] = args[1] factory_fields = set(kwargs) for key in self._pclass_fields: if key not in kwargs: value = getattr(self, key, _MISSING_VALUE) if value is not _MISSING_VALUE: kwargs[key] = value return self.__class__(_factory_fields=factory_fields, **kwargs) @classmethod def create(cls, kwargs, _factory_fields=None, ignore_extra=False): """ Factory method. Will create a new PClass of the current type and assign the values specified in kwargs. :param ignore_extra: A boolean which when set to True will ignore any keys which appear in kwargs that are not in the set of fields on the PClass. """ if isinstance(kwargs, cls): return kwargs if ignore_extra: kwargs = {k: kwargs[k] for k in cls._pclass_fields if k in kwargs} return cls(_factory_fields=_factory_fields, ignore_extra=ignore_extra, **kwargs) def serialize(self, format=None): """ Serialize the current PClass using custom serializer functions for fields where such have been supplied. """ result = {} for name in self._pclass_fields: value = getattr(self, name, _MISSING_VALUE) if value is not _MISSING_VALUE: result[name] = serialize(self._pclass_fields[name].serializer, format, value) return result def transform(self, *transformations): """ Apply transformations to the currency PClass. For more details on transformations see the documentation for PMap. Transformations on PClasses do not support key matching since the PClass is not a collection. Apart from that the transformations available for other persistent types work as expected. """ return transform(self, transformations) def __eq__(self, other): if isinstance(other, self.__class__): for name in self._pclass_fields: if getattr(self, name, _MISSING_VALUE) != getattr(other, name, _MISSING_VALUE): return False return True return NotImplemented def __ne__(self, other): return not self == other def __hash__(self): # May want to optimize this by caching the hash somehow return hash(tuple((key, getattr(self, key, _MISSING_VALUE)) for key in self._pclass_fields)) def __setattr__(self, key, value): if getattr(self, '_pclass_frozen', False): raise AttributeError("Can't set attribute, key={0}, value={1}".format(key, value)) super(PClass, self).__setattr__(key, value) def __delattr__(self, key): raise AttributeError("Can't delete attribute, key={0}, use remove()".format(key)) def _to_dict(self): result = {} for key in self._pclass_fields: value = getattr(self, key, _MISSING_VALUE) if value is not _MISSING_VALUE: result[key] = value return result def __repr__(self): return "{0}({1})".format(self.__class__.__name__, ', '.join('{0}={1}'.format(k, repr(v)) for k, v in self._to_dict().items())) def __reduce__(self): # Pickling support data = dict((key, getattr(self, key)) for key in self._pclass_fields if hasattr(self, key)) return _restore_pickle, (self.__class__, data,) def evolver(self): """ Returns an evolver for this object. """ return _PClassEvolver(self, self._to_dict()) def remove(self, name): """ Remove attribute given by name from the current instance. Raises AttributeError if the attribute doesn't exist. """ evolver = self.evolver() del evolver[name] return evolver.persistent()
PClass
python
google__jax
jax/_src/interpreters/partial_eval.py
{ "start": 116718, "end": 120231 }
class ____: ref: Any def __init__(self, tracer): self.ref = core.get_referent(tracer) def __eq__(self, other): return isinstance(other, TracerAsName) and self.ref is other.ref def __hash__(self): return id(self.ref) def _extract_implicit_args( trace: DynamicJaxprTrace, in_type: Sequence[tuple[AbstractValue, bool]], explicit_tracers: Sequence[DynamicJaxprTracer], source_info: SourceInfo, ) -> Sequence[DynamicJaxprTracer]: # First, construct a list to represent the full argument list, leaving the # implicit arguments as Nones for now. explicit_tracers_ = iter(explicit_tracers) tracers = [next(explicit_tracers_) if expl else None for _, expl in in_type] assert next(explicit_tracers_, None) is None del explicit_tracers_ # Next, populate the implicit arguments using DBIdxs in in_type. for i, (aval, explicit) in enumerate(in_type): if not explicit or not isinstance(aval, DShapedArray): continue # can't populate an implicit argument tracer = tracers[i] assert tracer is not None for d1, d2 in zip(aval.shape, tracer.aval.shape): if isinstance(d1, DBIdx): if tracers[d1.val] is None: tracers[d1.val] = trace.to_jaxpr_tracer(d2, source_info) assert tracers[d1.val] is trace.to_jaxpr_tracer(d2, source_info) assert all(t is not None for t in tracers) return [t for t, (_, e) in zip(tracers, in_type) if not e] # type: ignore def _input_type_to_tracers( new_arg: Callable[[AbstractValue | core.AvalQDD], Tracer], in_avals: Sequence[AbstractValue | core.AvalQDD] ) -> Sequence[Tracer]: # Create input Tracers given input AbstractValues, each of which can contain # DeBruijn indices which refer to positions in the input argument list. That # is, each element `a` of `in_avals` can have DBIdx instances in its shape, # which must refer to positions left of `a`'s. in_tracers: list[Tracer] = [] def _substitute_tracers_in_aval(a): if isinstance(a, DShapedArray) and any(type(d) is DBIdx for d in a.shape): shape = [in_tracers[d.val] if type(d) is DBIdx else d for d in a.shape] return a.update(shape=tuple(shape)) return a for a in in_avals: in_tracers.append(new_arg(_substitute_tracers_in_aval(a))) return in_tracers Const = Any Val = Any def pad_jaxpr(jaxpr: Jaxpr, consts: Sequence[Const] ) -> tuple[Jaxpr, list[Const]]: bounds = {v: v.aval.dtype.bound for v in jaxpr.invars if isinstance(v.aval, (core.ShapedArray, core.DShapedArray)) and type(v.aval.dtype) is core.bint and not v.aval.shape} idxs = {v: DBIdx(i) for i, v in enumerate(jaxpr.invars)} def substitute(aval: AbstractValue) -> AbstractValue: if (isinstance(aval, (core.ShapedArray, core.DShapedArray)) and type(aval.dtype) is core.bint and not aval.shape): return ShapedArray((), dtypes.scalar_type_to_dtype(int)) elif isinstance(aval, DShapedArray): shape = [bounds.get(d, idxs.get(d, d)) for d in aval.shape] # type: ignore typ = ShapedArray if all(type(d) is int for d in shape) else DShapedArray return typ(tuple(shape), aval.dtype, aval.weak_type) else: return aval in_avals = [substitute(v.aval) for v in jaxpr.invars] eval_padded = lu.wrap_init(partial(_eval_jaxpr_padded, jaxpr, consts), debug_info=jaxpr.debug_info) padded_jaxpr, _, padded_consts = trace_to_jaxpr_dynamic(eval_padded, in_avals) return padded_jaxpr, padded_consts
TracerAsName
python
HypothesisWorks__hypothesis
hypothesis-python/tests/cover/test_setup_teardown.py
{ "start": 1486, "end": 3084 }
class ____(HasSetup, HasTeardown, SomeGivens): pass def test_calls_setup_and_teardown_on_self_as_first_argument(): x = HasSetupAndTeardown() x.give_me_an_int() x.give_me_a_string() assert x.setups > 0 assert x.teardowns == x.setups def test_calls_setup_and_teardown_on_self_unbound(): x = HasSetupAndTeardown() HasSetupAndTeardown.give_me_an_int(x) assert x.setups > 0 assert x.teardowns == x.setups def test_calls_setup_and_teardown_on_failure(): x = HasSetupAndTeardown() with pytest.raises(AssertionError): x.give_me_a_positive_int() assert x.setups > 0 assert x.teardowns == x.setups def test_still_tears_down_on_error_in_generation(): x = HasSetupAndTeardown() with pytest.raises(AttributeError): x.fail_in_reify() assert x.setups > 0 assert x.teardowns == x.setups def test_still_tears_down_on_failed_assume(): x = HasSetupAndTeardown() x.assume_some_stuff() assert x.setups > 0 assert x.teardowns == x.setups def test_still_tears_down_on_failed_assume_in_reify(): x = HasSetupAndTeardown() x.assume_in_reify() assert x.setups > 0 assert x.teardowns == x.setups def test_sets_up_without_teardown(): class Foo(HasSetup, SomeGivens): pass x = Foo() x.give_me_an_int() assert x.setups > 0 assert not hasattr(x, "teardowns") def test_tears_down_without_setup(): class Foo(HasTeardown, SomeGivens): pass x = Foo() x.give_me_an_int() assert x.teardowns > 0 assert not hasattr(x, "setups")
HasSetupAndTeardown
python
getsentry__sentry
src/sentry/replays/usecases/ingest/event_parser.py
{ "start": 24163, "end": 24511 }
class ____(TypedDict, total=False): canvas_sizes: list[int] hydration_errors: list[HydrationError] mutations: list[MutationEvent] clicks: list[ClickEvent] multiclicks: list[MultiClickEvent] request_response_sizes: list[tuple[int | None, int | None]] options: list[dict[str, Any]] taps: list[TapEvent]
HighlightedEvents
python
matplotlib__matplotlib
lib/mpl_toolkits/axes_grid1/anchored_artists.py
{ "start": 443, "end": 2875 }
class ____(AnchoredOffsetbox): def __init__(self, width, height, xdescent, ydescent, loc, pad=0.4, borderpad=0.5, prop=None, frameon=True, **kwargs): """ An anchored container with a fixed size and fillable `.DrawingArea`. Artists added to the *drawing_area* will have their coordinates interpreted as pixels. Any transformations set on the artists will be overridden. Parameters ---------- width, height : float Width and height of the container, in pixels. xdescent, ydescent : float Descent of the container in the x- and y- direction, in pixels. loc : str Location of this artist. Valid locations are 'upper left', 'upper center', 'upper right', 'center left', 'center', 'center right', 'lower left', 'lower center', 'lower right'. For backward compatibility, numeric values are accepted as well. See the parameter *loc* of `.Legend` for details. pad : float, default: 0.4 Padding around the child objects, in fraction of the font size. borderpad : float, default: 0.5 Border padding, in fraction of the font size. prop : `~matplotlib.font_manager.FontProperties`, optional Font property used as a reference for paddings. frameon : bool, default: True If True, draw a box around this artist. **kwargs Keyword arguments forwarded to `.AnchoredOffsetbox`. Attributes ---------- drawing_area : `~matplotlib.offsetbox.DrawingArea` A container for artists to display. Examples -------- To display blue and red circles of different sizes in the upper right of an Axes *ax*: >>> ada = AnchoredDrawingArea(20, 20, 0, 0, ... loc='upper right', frameon=False) >>> ada.drawing_area.add_artist(Circle((10, 10), 10, fc="b")) >>> ada.drawing_area.add_artist(Circle((30, 10), 5, fc="r")) >>> ax.add_artist(ada) """ self.da = DrawingArea(width, height, xdescent, ydescent) self.drawing_area = self.da super().__init__( loc, pad=pad, borderpad=borderpad, child=self.da, prop=None, frameon=frameon, **kwargs )
AnchoredDrawingArea
python
apache__airflow
scripts/in_container/run_template_fields_check.py
{ "start": 1478, "end": 6403 }
class ____(ast.NodeVisitor): def __init__(self): self.current_class = None self.instance_fields = [] def visit_FunctionDef(self, node: ast.FunctionDef) -> ast.FunctionDef: if node.name == "__init__": self.generic_visit(node) return node def visit_Assign(self, node: ast.Assign) -> ast.Assign: fields = [] for target in node.targets: if isinstance(target, ast.Attribute): fields.append(target.attr) if fields: self.instance_fields.extend(fields) return node def visit_AnnAssign(self, node: ast.AnnAssign) -> ast.AnnAssign: if isinstance(node.target, ast.Attribute): self.instance_fields.append(node.target.attr) return node def get_template_fields_and_class_instance_fields(cls): """ 1.This method retrieves the operator class and obtains all its parent classes using the method resolution order (MRO). 2. It then gathers the templated fields declared in both the operator class and its parent classes. 3. Finally, it retrieves the instance fields of the operator class, specifically the self.fields attributes. """ all_template_fields = [] class_instance_fields = [] all_classes = cls.__mro__ for current_class in all_classes: if current_class.__init__ is not object.__init__: cls_attr = current_class.__dict__ for template_type in TEMPLATE_TYPES: fields = cls_attr.get(template_type) if fields: all_template_fields.extend(fields) tree = ast.parse(inspect.getsource(current_class)) visitor = InstanceFieldExtractor() visitor.visit(tree) if visitor.instance_fields: class_instance_fields.extend(visitor.instance_fields) return all_template_fields, class_instance_fields def load_yaml_data() -> dict: """ It loads all the provider YAML files and retrieves the module referenced within each YAML file. """ package_paths = sorted(str(path) for path in provider_files_pattern) result = {} for provider_yaml_path in package_paths: with open(provider_yaml_path) as yaml_file: provider = yaml.load(yaml_file, SafeLoader) rel_path = pathlib.Path(provider_yaml_path).relative_to(ROOT_DIR).as_posix() result[rel_path] = provider return result def get_providers_modules() -> list[str]: modules_container = [] result = load_yaml_data() for (_, provider_data), resource_type in itertools.product(result.items(), OPERATORS): if provider_data.get(resource_type): for data in provider_data.get(resource_type): modules_container.extend(data.get("python-modules")) return modules_container def is_class_eligible(name: str) -> bool: for op in CLASS_IDENTIFIERS: if name.lower().endswith(op): return True return False def get_eligible_classes(all_classes): """ Filter the results to include only classes that end with `Sensor` or `Operator`. """ eligible_classes = [(name, cls) for name, cls in all_classes if is_class_eligible(name)] return eligible_classes def iter_check_template_fields(module: str): """ 1. This method imports the providers module and retrieves all the classes defined within it. 2. It then filters and selects classes related to operators or sensors by checking if the class name ends with "Operator" or "Sensor." 3. For each operator class, it validates the template fields by inspecting the class instance fields. """ with warnings.catch_warnings(record=True): imported_module = importlib.import_module(module) classes = inspect.getmembers(imported_module, inspect.isclass) op_classes = get_eligible_classes(classes) for op_class_name, cls in op_classes: if cls.__module__ == module: templated_fields, class_instance_fields = get_template_fields_and_class_instance_fields(cls) for field in templated_fields: if field not in class_instance_fields: errors.append(f"{module}: {op_class_name}: {field}") if __name__ == "__main__": provider_modules = get_providers_modules() if len(sys.argv) > 1: py_files = sorted(sys.argv[1:]) modules_to_validate = [ module_name for pyfile in py_files if (module_name := pyfile.rstrip(".py").replace("/", ".")) in provider_modules ] else: modules_to_validate = provider_modules [iter_check_template_fields(module) for module in modules_to_validate] if errors: console.print("[red]Found Invalid template fields:") for error in errors: console.print(f"[red]Error:[/] {error}") sys.exit(len(errors))
InstanceFieldExtractor
python
kamyu104__LeetCode-Solutions
Python/house-robber-ii.py
{ "start": 29, "end": 594 }
class ____(object): # @param {integer[]} nums # @return {integer} def rob(self, nums): if len(nums) == 0: return 0 if len(nums) == 1: return nums[0] return max(self.robRange(nums, 0, len(nums) - 1),\ self.robRange(nums, 1, len(nums))) def robRange(self, nums, start, end): num_i, num_i_1 = nums[start], 0 for i in xrange(start + 1, end): num_i_1, num_i_2 = num_i, num_i_1 num_i = max(nums[i] + num_i_2, num_i_1) return num_i
Solution
python
realpython__materials
python-with-statement/hello.py
{ "start": 0, "end": 514 }
class ____: def __enter__(self): print("Entering the context...") return "Hello, World!" def __exit__(self, exc_type, exc_value, exc_tb): print("Leaving the context...") print(f"{exc_type = }") print(f"{exc_value = }") print(f"{exc_tb = }") if __name__ == "__main__": with HelloContextManager() as hello: print(hello) print("Continue normally from here...") with HelloContextManager() as hello: hello[100]
HelloContextManager
python
PyCQA__pylint
tests/functional/r/regression_02/regression_5030.py
{ "start": 488, "end": 603 }
class ____: """A dataclass.""" a_dict: Dict[str, List[str]] = field(default_factory=dict) @dataclass
SomeData
python
PrefectHQ__prefect
tests/test_exceptions.py
{ "start": 233, "end": 286 }
class ____(BaseModel): num: int string: str
Foo
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/utils/eks_test_constants.py
{ "start": 4875, "end": 5159 }
class ____: """Key names for the dictionaries representing EKS Clusters.""" ARN = "arn" CLUSTER_NAME = "clusterName" CREATED_AT = "createdAt" ENDPOINT = "endpoint" IDENTITY = "identity" ISSUER = "issuer" NAME = "name" OIDC = "oidc"
ClusterAttributes
python
networkx__networkx
networkx/exception.py
{ "start": 1824, "end": 1993 }
class ____(NetworkXUnfeasible): """Exception for algorithms that should return a cycle when running on graphs where such a cycle does not exist."""
NetworkXNoCycle
python
pytorch__pytorch
test/dynamo/test_subclasses.py
{ "start": 104367, "end": 105406 }
class ____(torch.nn.Module): def forward( self, primals_1: "f32[3, 4]", # SubclassGetAttrAOTInput(base=PlainAOTInput(idx=0), attr='a') primals_2: "f32[3, 4]", # SubclassGetAttrAOTInput(base=PlainAOTInput(idx=0), attr='b') ): clone: "f32[3, 4]" = torch.ops.aten.clone.default(primals_1); primals_1 = None clone_1: "f32[3, 4]" = torch.ops.aten.clone.default(primals_2); primals_2 = None view: "f32[12]" = torch.ops.aten.view.default(clone, [-1]) view_1: "f32[12]" = torch.ops.aten.view.default(clone_1, [-1]) return ( clone, # PlainAOTOutput(idx=0) view, # SubclassGetAttrAOTOutput(base=PlainAOTOutput(idx=1), attr='a') view_1, # SubclassGetAttrAOTOutput(base=PlainAOTOutput(idx=1), attr='b') clone_1, # PlainAOTOutput(idx=2) ) """, # noqa: B950 ) self.assertExpectedInline( normalize_gm(fw[1].print_readable(print_output=False, expanded_def=True)), """\
GraphModule
python
getsentry__sentry
tests/sentry/integrations/api/endpoints/test_organization_integration_issues.py
{ "start": 93, "end": 1502 }
class ____(APITestCase): def setUp(self) -> None: super().setUp() self.login_as(self.user) self.organization = self.create_organization(owner=self.user) def get_path(self, integration_id): return ( f"/api/0/organizations/{self.organization.slug}/integrations/{integration_id}/issues/" ) def test_no_integration(self) -> None: path = self.get_path(integration_id=-1) response = self.client.put(path, format="json") assert response.status_code == 404 def test_not_issue_integration(self) -> None: integration = self.create_integration( organization=self.organization, provider="slack", external_id="slack:1" ) path = self.get_path(integration_id=integration.id) response = self.client.put(path, format="json") assert response.status_code == 400 @patch("sentry.integrations.jira.integration.JiraIntegration.migrate_issues") def test_simple(self, mock_migrate_issues: MagicMock) -> None: integration = self.create_integration( organization=self.organization, provider="jira", external_id="jira:1" ) path = self.get_path(integration_id=integration.id) response = self.client.put(path, format="json") assert response.status_code == 204 assert mock_migrate_issues.called
OrganizationIntegrationIssuesTest
python
huggingface__transformers
tests/models/yolos/test_image_processing_yolos.py
{ "start": 1219, "end": 5250 }
class ____: def __init__( self, parent, batch_size=7, num_channels=3, min_resolution=30, max_resolution=400, do_resize=True, size=None, do_normalize=True, image_mean=[0.5, 0.5, 0.5], image_std=[0.5, 0.5, 0.5], do_rescale=True, rescale_factor=1 / 255, do_pad=True, ): # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p size = size if size is not None else {"shortest_edge": 18, "longest_edge": 1333} self.parent = parent self.batch_size = batch_size self.num_channels = num_channels self.min_resolution = min_resolution self.max_resolution = max_resolution self.do_resize = do_resize self.size = size self.do_normalize = do_normalize self.image_mean = image_mean self.image_std = image_std self.do_rescale = do_rescale self.rescale_factor = rescale_factor self.do_pad = do_pad def prepare_image_processor_dict(self): return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def get_expected_values(self, image_inputs, batched=False): """ This function computes the expected height and width when providing images to YolosImageProcessor, assuming do_resize is set to True with a scalar size. """ if not batched: image = image_inputs[0] if isinstance(image, Image.Image): width, height = image.size elif isinstance(image, np.ndarray): height, width = image.shape[0], image.shape[1] else: height, width = image.shape[1], image.shape[2] size = self.size["shortest_edge"] max_size = self.size.get("longest_edge", None) if max_size is not None: min_original_size = float(min((height, width))) max_original_size = float(max((height, width))) if max_original_size / min_original_size * size > max_size: size = int(round(max_size * min_original_size / max_original_size)) if width <= height and width != size: height = int(size * height / width) width = size elif height < width and height != size: width = int(size * width / height) height = size width_mod = width % 16 height_mod = height % 16 expected_width = width - width_mod expected_height = height - height_mod else: expected_values = [] for image in image_inputs: expected_height, expected_width = self.get_expected_values([image]) expected_values.append((expected_height, expected_width)) expected_height = max(expected_values, key=lambda item: item[0])[0] expected_width = max(expected_values, key=lambda item: item[1])[1] return expected_height, expected_width def expected_output_image_shape(self, images): height, width = self.get_expected_values(images, batched=True) return self.num_channels, height, width def prepare_image_inputs(self, equal_resolution=False, numpify=False, torchify=False): return prepare_image_inputs( batch_size=self.batch_size, num_channels=self.num_channels, min_resolution=self.min_resolution, max_resolution=self.max_resolution, equal_resolution=equal_resolution, numpify=numpify, torchify=torchify, ) @require_torch @require_vision
YolosImageProcessingTester
python
aio-libs__aiohttp
aiohttp/web_runner.py
{ "start": 5113, "end": 6258 }
class ____(BaseSite): __slots__ = ("_sock", "_name") def __init__( self, runner: "BaseRunner[Any]", sock: socket.socket, *, ssl_context: SSLContext | None = None, backlog: int = 128, ) -> None: super().__init__( runner, ssl_context=ssl_context, backlog=backlog, ) self._sock = sock scheme = "https" if self._ssl_context else "http" if hasattr(socket, "AF_UNIX") and sock.family == socket.AF_UNIX: name = f"{scheme}://unix:{sock.getsockname()}:" else: host, port = sock.getsockname()[:2] name = str(URL.build(scheme=scheme, host=host, port=port)) self._name = name @property def name(self) -> str: return self._name async def start(self) -> None: await super().start() loop = asyncio.get_event_loop() server = self._runner.server assert server is not None self._server = await loop.create_server( server, sock=self._sock, ssl=self._ssl_context, backlog=self._backlog )
SockSite
python
huggingface__transformers
tests/models/llava_next/test_image_processing_llava_next.py
{ "start": 1309, "end": 3704 }
class ____: def __init__( self, parent, batch_size=7, num_channels=3, image_size=18, min_resolution=30, max_resolution=400, do_resize=True, size=None, do_center_crop=True, crop_size=None, do_normalize=True, image_mean=OPENAI_CLIP_MEAN, image_std=OPENAI_CLIP_STD, do_convert_rgb=True, ): super().__init__() size = size if size is not None else {"shortest_edge": 20} crop_size = crop_size if crop_size is not None else {"height": 18, "width": 18} self.parent = parent self.batch_size = batch_size self.num_channels = num_channels self.image_size = image_size self.min_resolution = min_resolution self.max_resolution = max_resolution self.do_resize = do_resize self.size = size self.do_center_crop = do_center_crop self.crop_size = crop_size self.do_normalize = do_normalize self.image_mean = image_mean self.image_std = image_std self.do_convert_rgb = do_convert_rgb def prepare_image_processor_dict(self): return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_convert_rgb": self.do_convert_rgb, } # Copied from tests.models.clip.test_image_processing_clip.CLIPImageProcessingTester.expected_output_image_shape def expected_output_image_shape(self, images): return self.num_channels, self.crop_size["height"], self.crop_size["width"] # Copied from tests.models.clip.test_image_processing_clip.CLIPImageProcessingTester.prepare_image_inputs def prepare_image_inputs(self, equal_resolution=False, numpify=False, torchify=False): return prepare_image_inputs( batch_size=self.batch_size, num_channels=self.num_channels, min_resolution=self.min_resolution, max_resolution=self.max_resolution, equal_resolution=equal_resolution, numpify=numpify, torchify=torchify, ) @require_torch @require_vision
LlavaNextImageProcessingTester
python
fsspec__filesystem_spec
fsspec/tests/abstract/pipe.py
{ "start": 16, "end": 402 }
class ____: def test_pipe_exclusive(self, fs, fs_target): fs.pipe_file(fs_target, b"data") assert fs.cat_file(fs_target) == b"data" with pytest.raises(FileExistsError): fs.pipe_file(fs_target, b"data", mode="create") fs.pipe_file(fs_target, b"new data", mode="overwrite") assert fs.cat_file(fs_target) == b"new data"
AbstractPipeTests
python
prompt-toolkit__python-prompt-toolkit
src/prompt_toolkit/mouse_events.py
{ "start": 1854, "end": 2473 }
class ____: """ Mouse event, sent to `UIControl.mouse_handler`. :param position: `Point` instance. :param event_type: `MouseEventType`. """ def __init__( self, position: Point, event_type: MouseEventType, button: MouseButton, modifiers: frozenset[MouseModifier], ) -> None: self.position = position self.event_type = event_type self.button = button self.modifiers = modifiers def __repr__(self) -> str: return f"MouseEvent({self.position!r},{self.event_type!r},{self.button!r},{self.modifiers!r})"
MouseEvent
python
charliermarsh__ruff
crates/ruff_python_parser/resources/inline/err/duplicate_type_parameter_names.py
{ "start": 46, "end": 261 }
class ____[T, T]: ... type Alias[T, U: str, V: (str, bytes), *Ts, **P, T = default] = ... def f[T, T, T](): ... # two errors def f[T, *T](): ... # star is still duplicate def f[T, **T](): ... # as is double star
C
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/classes5.py
{ "start": 4210, "end": 4989 }
class ____(ParentClass2): cv_decl_1 = 1 # This should generate an error. cv_decl_2 = "" # This should generate an error. cv_decl_3 = None cv_infer_1 = 3 cv_infer_2 = "" cv_infer_3 = None def __init__(self): self.cv_decl_4 = 1 # This should generate an error. self.cv_decl_5 = "" # This should generate an error. self.cv_decl_6 = None self.cv_infer_4 = 1 self.cv_infer_5 = "" self.cv_infer_6 = None self.iv_decl_1 = 1 # This should generate an error. self.iv_decl_2 = "" # This should generate an error. self.iv_decl_3 = None self.iv_infer_1 = 1 self.iv_infer_2 = "" self.iv_infer_3 = None
SubclassInferred2
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/bigquery_dts.py
{ "start": 2139, "end": 6433 }
class ____(GoogleCloudBaseOperator): """ Creates a new data transfer configuration. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:BigQueryCreateDataTransferOperator` :param transfer_config: Data transfer configuration to create. :param project_id: The BigQuery project id where the transfer configuration should be created. If set to None or missing, the default project_id from the Google Cloud connection is used. :param location: BigQuery Transfer Service location for regional transfers. :param authorization_code: authorization code to use with this transfer configuration. This is required if new credentials are needed. :param retry: A retry object used to retry requests. If `None` is specified, requests will not be retried. :param timeout: The amount of time, in seconds, to wait for the request to complete. Note that if retry is specified, the timeout applies to each individual attempt. :param metadata: Additional metadata that is provided to the method. :param gcp_conn_id: The connection ID used to connect to Google Cloud. :param impersonation_chain: Optional service account to impersonate using short-term credentials, or chained list of accounts required to get the access_token of the last account in the list, which will be impersonated in the request. If set as a string, the account must grant the originating account the Service Account Token Creator IAM role. If set as a sequence, the identities from the list must grant Service Account Token Creator IAM role to the directly preceding identity, with first account from the list granting this role to the originating account (templated). """ template_fields: Sequence[str] = ( "transfer_config", "project_id", "authorization_code", "gcp_conn_id", "impersonation_chain", ) operator_extra_links = (BigQueryDataTransferConfigLink(),) def __init__( self, *, transfer_config: dict, project_id: str = PROVIDE_PROJECT_ID, location: str | None = None, authorization_code: str | None = None, retry: Retry | _MethodDefault = DEFAULT, timeout: float | None = None, metadata: Sequence[tuple[str, str]] = (), gcp_conn_id="google_cloud_default", impersonation_chain: str | Sequence[str] | None = None, **kwargs, ) -> None: super().__init__(**kwargs) self.transfer_config = transfer_config self.authorization_code = authorization_code self.project_id = project_id self.location = location self.retry = retry self.timeout = timeout self.metadata = metadata self.gcp_conn_id = gcp_conn_id self.impersonation_chain = impersonation_chain def execute(self, context: Context): hook = BiqQueryDataTransferServiceHook( gcp_conn_id=self.gcp_conn_id, impersonation_chain=self.impersonation_chain, location=self.location ) self.log.info("Creating DTS transfer config") response = hook.create_transfer_config( project_id=self.project_id, transfer_config=self.transfer_config, authorization_code=self.authorization_code, retry=self.retry, timeout=self.timeout, metadata=self.metadata, ) transfer_config = _get_transfer_config_details(response.name) BigQueryDataTransferConfigLink.persist( context=context, region=transfer_config["region"], config_id=transfer_config["config_id"], project_id=transfer_config["project_id"], ) result = TransferConfig.to_dict(response) self.log.info("Created DTS transfer config %s", get_object_id(result)) context["ti"].xcom_push(key="transfer_config_id", value=get_object_id(result)) # don't push AWS secret in XCOM result.get("params", {}).pop("secret_access_key", None) result.get("params", {}).pop("access_key_id", None) return result
BigQueryCreateDataTransferOperator
python
kamyu104__LeetCode-Solutions
Python/find-first-palindromic-string-in-the-array.py
{ "start": 29, "end": 550 }
class ____(object): def firstPalindrome(self, words): """ :type words: List[str] :rtype: str """ def is_palindrome(s): i, j = 0, len(s)-1 while i < j: if s[i] != s[j]: return False i += 1 j -= 1 return True for w in words: if is_palindrome(w): return w return "" # Time: O(n) # Space: O(l), l is the max length of words
Solution
python
anthropics__anthropic-sdk-python
src/anthropic/types/content_block_source_param.py
{ "start": 338, "end": 509 }
class ____(TypedDict, total=False): content: Required[Union[str, Iterable[ContentBlockSourceContentParam]]] type: Required[Literal["content"]]
ContentBlockSourceParam
python
wandb__wandb
wandb/vendor/pygments/lexers/erlang.py
{ "start": 5972, "end": 8173 }
class ____(Lexer): """ Shell sessions in erl (for Erlang code). .. versionadded:: 1.1 """ name = 'Erlang erl session' aliases = ['erl'] filenames = ['*.erl-sh'] mimetypes = ['text/x-erl-shellsession'] _prompt_re = re.compile(r'\d+>(?=\s|\Z)') def get_tokens_unprocessed(self, text): erlexer = ErlangLexer(**self.options) curcode = '' insertions = [] for match in line_re.finditer(text): line = match.group() m = self._prompt_re.match(line) if m is not None: end = m.end() insertions.append((len(curcode), [(0, Generic.Prompt, line[:end])])) curcode += line[end:] else: if curcode: for item in do_insertions(insertions, erlexer.get_tokens_unprocessed(curcode)): yield item curcode = '' insertions = [] if line.startswith('*'): yield match.start(), Generic.Traceback, line else: yield match.start(), Generic.Output, line if curcode: for item in do_insertions(insertions, erlexer.get_tokens_unprocessed(curcode)): yield item def gen_elixir_string_rules(name, symbol, token): states = {} states['string_' + name] = [ (r'[^#%s\\]+' % (symbol,), token), include('escapes'), (r'\\.', token), (r'(%s)' % (symbol,), bygroups(token), "#pop"), include('interpol') ] return states def gen_elixir_sigstr_rules(term, token, interpol=True): if interpol: return [ (r'[^#%s\\]+' % (term,), token), include('escapes'), (r'\\.', token), (r'%s[a-zA-Z]*' % (term,), token, '#pop'), include('interpol') ] else: return [ (r'[^%s\\]+' % (term,), token), (r'\\.', token), (r'%s[a-zA-Z]*' % (term,), token, '#pop'), ]
ErlangShellLexer
python
google__pytype
pytype/abstract/_instances.py
{ "start": 26890, "end": 27740 }
class ____(_base.BaseValue): """Representation of unpacked iterables.""" def __init__(self, ctx: "context.Context", iterable: cfg.Variable) -> None: super().__init__("splat", ctx) # When building a tuple for a function call, we preserve splats as elements # in a concrete tuple (e.g. f(x, *ys, z) gets called with the concrete tuple # (x, *ys, z) in starargs) and let the arg matcher in function.py unpack # them. Constructing the tuple accesses its class as a side effect; ideally # we would specialise abstract.Tuple for function calls and not bother # constructing an associated TupleClass for a function call tuple, but for # now we just set the class to Any here. self.cls = ctx.convert.unsolvable self.iterable = iterable def __repr__(self) -> str: return f"splat({self.iterable.data!r})"
Splat
python
davidhalter__parso
test/test_normalizer_issues_files.py
{ "start": 285, "end": 2284 }
class ____: def __init__(self, code: str, line: int, column: int) -> None: self.code = code self._line = line self._column = column def __eq__(self, other): return self.code == other.code and self.start_pos == other.start_pos def __lt__(self, other: 'WantedIssue') -> bool: return self.start_pos < other.start_pos or self.code < other.code def __hash__(self) -> int: return hash(str(self.code) + str(self._line) + str(self._column)) @property def start_pos(self) -> Tuple[int, int]: return self._line, self._column def collect_errors(code: str) -> Iterator[WantedIssue]: for line_nr, line in enumerate(code.splitlines(), 1): match = re.match(r'(\s*)#: (.*)$', line) if match is not None: codes = match.group(2) for code in codes.split(): code, _, add_indent = code.partition(':') column = int(add_indent or len(match.group(1))) code, _, add_line = code.partition('+') ln = line_nr + 1 + int(add_line or 0) yield WantedIssue(code[1:], ln, column) def test_normalizer_issue(normalizer_issue_case): def sort(issues): issues = sorted(issues, key=lambda i: (i.start_pos, i.code)) return ["(%s, %s): %s" % (i.start_pos[0], i.start_pos[1], i.code) for i in issues] with open(normalizer_issue_case.path, 'rb') as f: code = python_bytes_to_unicode(f.read()) desired = sort(collect_errors(code)) grammar = parso.load_grammar(version=normalizer_issue_case.python_version) module = grammar.parse(code) issues = grammar._get_normalizer_issues(module) actual = sort(issues) diff = '\n'.join(difflib.ndiff(desired, actual)) # To make the pytest -v diff a bit prettier, stop pytest to rewrite assert # statements by executing the comparison earlier. _bool = desired == actual assert _bool, '\n' + diff
WantedIssue
python
ray-project__ray
doc/source/serve/doc_code/streaming_tutorial.py
{ "start": 6345, "end": 6975 }
class ____: def __init__(self, timeout: float = None): self.q = Queue() self.stop_signal = None self.timeout = timeout def put(self, values): self.q.put(values) def end(self): self.q.put(self.stop_signal) def __iter__(self): return self def __next__(self): result = self.q.get(timeout=self.timeout) if result == self.stop_signal: raise StopIteration() else: return result # __raw_streamer_end__ # __batchbot_constructor_start__ fastapi_app = FastAPI() @serve.deployment @serve.ingress(fastapi_app)
RawStreamer
python
google__jax
tests/tree_util_test.py
{ "start": 4751, "end": 6156 }
class ____: """Stores a value but pretends to be equal to every other black box.""" value: int def __hash__(self): return 0 def __eq__(self, other): return isinstance(other, BlackBox) TREES = ( (None,), ((None,),), ((),), (([()]),), ((1, 2),), (((1, "foo"), ["bar", (3, None, 7)]),), ([3],), ([3, ATuple(foo=(3, ATuple(foo=3, bar=None)), bar={"baz": 34})],), ([AnObject(3, None, [4, "foo"])],), ([AnObject2(3, None, [4, "foo"])],), (Special(2, 3.0),), ({"a": 1, "b": 2},), (StaticInt(1),), (StaticTuple((2, 3)),), (StaticDict(foo=4, bar=5),), ) TREE_STRINGS = ( "PyTreeDef(None)", "PyTreeDef((None,))", "PyTreeDef(())", "PyTreeDef([()])", "PyTreeDef((*, *))", "PyTreeDef(((*, *), [*, (*, None, *)]))", "PyTreeDef([*])", ("PyTreeDef([*, CustomNode(namedtuple[ATuple], [(*, " "CustomNode(namedtuple[ATuple], [*, None])), {'baz': *}])])"), "PyTreeDef([CustomNode(AnObject[[4, 'foo']], [*, None])])", "PyTreeDef([CustomNode(AnObject2[[4, 'foo']], [*, None])])", "PyTreeDef(CustomNode(Special[None], [*, *]))", "PyTreeDef({'a': *, 'b': *})", "PyTreeDef(CustomNode(StaticInt[1], []))", "PyTreeDef(CustomNode(StaticTuple[(2, 3)], []))", "PyTreeDef(CustomNode(StaticDict[{'foo': 4, 'bar': 5}], []))", ) @jax.tree_util.register_dataclass @dataclasses.dataclass
BlackBox
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chart_gridlines06.py
{ "start": 315, "end": 1816 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chart_gridlines06.xlsx") def test_create_file(self): """Test XlsxWriter gridlines.""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() chart = workbook.add_chart({"type": "scatter"}) chart.axis_ids = [82812288, 46261376] data = [ [1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 6, 9, 12, 15], ] worksheet.write_column("A1", data[0]) worksheet.write_column("B1", data[1]) worksheet.write_column("C1", data[2]) chart.add_series( { "categories": "=Sheet1!$A$1:$A$5", "values": "=Sheet1!$B$1:$B$5", } ) chart.add_series( { "categories": "=Sheet1!$A$1:$A$5", "values": "=Sheet1!$C$1:$C$5", } ) chart.set_x_axis( { "major_gridlines": {"visible": 1}, "minor_gridlines": {"visible": 1}, } ) chart.set_y_axis( { "major_gridlines": {"visible": 1}, "minor_gridlines": {"visible": 1}, } ) worksheet.insert_chart("E9", chart) workbook.close() self.assertExcelEqual()
TestCompareXLSXFiles
python
pennersr__django-allauth
allauth/socialaccount/providers/weibo/provider.py
{ "start": 520, "end": 990 }
class ____(OAuth2Provider): id = "weibo" name = "Weibo" account_class = WeiboAccount oauth2_adapter_class = WeiboOAuth2Adapter def extract_uid(self, data): ret = data.get("idstr") if not ret: raise ProviderException("Missing 'idstr'") return ret def extract_common_fields(self, data): return dict(username=data.get("screen_name"), name=data.get("name")) provider_classes = [WeiboProvider]
WeiboProvider
python
django-extensions__django-extensions
tests/management/commands/test_reset_schema.py
{ "start": 1269, "end": 2483 }
class ____(TestCase): """Tests for reset_chema command.""" def test_should_drop_schema_and_create_new_one(self): m_cursor = mock.Mock() m_router = mock.Mock() m_router.cursor.return_value = mock.Mock( __enter__=mock.Mock(return_value=m_cursor), __exit__=mock.Mock(return_value=False), ) expected_calls = [ mock.call("DROP SCHEMA test_public CASCADE"), mock.call("CREATE SCHEMA test_public"), ] with mock.patch( "django_extensions.management.commands.reset_schema.connections", {"default": m_router}, ): call_command("reset_schema", "--noinput", "--schema=test_public") m_cursor.execute.assert_has_calls(expected_calls, any_order=False) @mock.patch("sys.stdout", new_callable=StringIO) @mock.patch("django_extensions.management.commands.reset_schema.input") def test_should_cancel_reset_schema_and_print_info_if_input_is_different_than_yes( self, m_input, m_stdout ): m_input.return_value = "no" call_command("reset_schema") self.assertEqual("Reset cancelled.\n", m_stdout.getvalue())
ResetSchemaTests
python
numba__numba
numba/core/types/misc.py
{ "start": 7142, "end": 7229 }
class ____(Opaque): """ The type for the Ellipsis singleton. """
EllipsisType
python
sympy__sympy
sympy/assumptions/predicates/matrices.py
{ "start": 10972, "end": 11635 }
class ____(Predicate): """ Triangular matrix predicate. Explanation =========== ``Q.triangular(X)`` is true if ``X`` is one that is either lower triangular or upper triangular. Examples ======== >>> from sympy import Q, ask, MatrixSymbol >>> X = MatrixSymbol('X', 4, 4) >>> ask(Q.triangular(X), Q.upper_triangular(X)) True >>> ask(Q.triangular(X), Q.lower_triangular(X)) True References ========== .. [1] https://en.wikipedia.org/wiki/Triangular_matrix """ name = "triangular" handler = Dispatcher("TriangularHandler", doc="Predicate fore key 'triangular'.")
TriangularPredicate
python
django__django
tests/generic_views/test_dates.py
{ "start": 23591, "end": 29694 }
class ____(TestDataMixin, TestCase): def test_week_view(self): res = self.client.get("/dates/books/2008/week/39/") self.assertEqual(res.status_code, 200) self.assertTemplateUsed(res, "generic_views/book_archive_week.html") self.assertEqual( res.context["book_list"][0], Book.objects.get(pubdate=datetime.date(2008, 10, 1)), ) self.assertEqual(res.context["week"], datetime.date(2008, 9, 28)) # Since allow_empty=False, next/prev weeks must be valid self.assertIsNone(res.context["next_week"]) self.assertEqual(res.context["previous_week"], datetime.date(2006, 4, 30)) def test_week_view_allow_empty(self): # allow_empty = False, empty week res = self.client.get("/dates/books/2008/week/12/") self.assertEqual(res.status_code, 404) # allow_empty = True, empty month res = self.client.get("/dates/books/2008/week/12/allow_empty/") self.assertEqual(res.status_code, 200) self.assertEqual(list(res.context["book_list"]), []) self.assertEqual(res.context["week"], datetime.date(2008, 3, 23)) # Since allow_empty=True, next/prev are allowed to be empty weeks self.assertEqual(res.context["next_week"], datetime.date(2008, 3, 30)) self.assertEqual(res.context["previous_week"], datetime.date(2008, 3, 16)) # allow_empty but not allow_future: next_week should be empty url = ( datetime.date.today() .strftime("/dates/books/%Y/week/%U/allow_empty/") .lower() ) res = self.client.get(url) self.assertEqual(res.status_code, 200) self.assertIsNone(res.context["next_week"]) def test_week_view_allow_future(self): # January 7th always falls in week 1, given Python's definition of week # numbers future = datetime.date(datetime.date.today().year + 1, 1, 7) future_sunday = future - datetime.timedelta(days=(future.weekday() + 1) % 7) b = Book.objects.create(name="The New New Testement", pages=600, pubdate=future) res = self.client.get("/dates/books/%s/week/1/" % future.year) self.assertEqual(res.status_code, 404) res = self.client.get("/dates/books/%s/week/1/allow_future/" % future.year) self.assertEqual(res.status_code, 200) self.assertEqual(list(res.context["book_list"]), [b]) self.assertEqual(res.context["week"], future_sunday) # Since allow_future = True but not allow_empty, next/prev are not # allowed to be empty weeks self.assertIsNone(res.context["next_week"]) self.assertEqual(res.context["previous_week"], datetime.date(2008, 9, 28)) # allow_future, but not allow_empty, with a current week. So next # should be in the future res = self.client.get("/dates/books/2008/week/39/allow_future/") self.assertEqual(res.status_code, 200) self.assertEqual(res.context["next_week"], future_sunday) self.assertEqual(res.context["previous_week"], datetime.date(2006, 4, 30)) def test_week_view_paginated(self): week_start = datetime.date(2008, 9, 28) week_end = week_start + datetime.timedelta(days=7) res = self.client.get("/dates/books/2008/week/39/") self.assertEqual(res.status_code, 200) self.assertEqual( list(res.context["book_list"]), list(Book.objects.filter(pubdate__gte=week_start, pubdate__lt=week_end)), ) self.assertEqual( list(res.context["object_list"]), list(Book.objects.filter(pubdate__gte=week_start, pubdate__lt=week_end)), ) self.assertTemplateUsed(res, "generic_views/book_archive_week.html") def test_week_view_invalid_pattern(self): res = self.client.get("/dates/books/2007/week/no_week/") self.assertEqual(res.status_code, 404) def test_week_start_Monday(self): # Regression for #14752 res = self.client.get("/dates/books/2008/week/39/") self.assertEqual(res.status_code, 200) self.assertEqual(res.context["week"], datetime.date(2008, 9, 28)) res = self.client.get("/dates/books/2008/week/39/monday/") self.assertEqual(res.status_code, 200) self.assertEqual(res.context["week"], datetime.date(2008, 9, 29)) def test_week_iso_format(self): res = self.client.get("/dates/books/2008/week/40/iso_format/") self.assertEqual(res.status_code, 200) self.assertTemplateUsed(res, "generic_views/book_archive_week.html") self.assertEqual( list(res.context["book_list"]), [Book.objects.get(pubdate=datetime.date(2008, 10, 1))], ) self.assertEqual(res.context["week"], datetime.date(2008, 9, 29)) def test_unknown_week_format(self): msg = "Unknown week format '%T'. Choices are: %U, %V, %W" with self.assertRaisesMessage(ValueError, msg): self.client.get("/dates/books/2008/week/39/unknown_week_format/") def test_incompatible_iso_week_format_view(self): msg = ( "ISO week directive '%V' is incompatible with the year directive " "'%Y'. Use the ISO year '%G' instead." ) with self.assertRaisesMessage(ValueError, msg): self.client.get("/dates/books/2008/week/40/invalid_iso_week_year_format/") def test_datetime_week_view(self): BookSigning.objects.create(event_date=datetime.datetime(2008, 4, 2, 12, 0)) res = self.client.get("/dates/booksignings/2008/week/13/") self.assertEqual(res.status_code, 200) @override_settings(USE_TZ=True, TIME_ZONE="Africa/Nairobi") def test_aware_datetime_week_view(self): BookSigning.objects.create( event_date=datetime.datetime(2008, 4, 2, 12, 0, tzinfo=datetime.UTC) ) res = self.client.get("/dates/booksignings/2008/week/13/") self.assertEqual(res.status_code, 200) @override_settings(ROOT_URLCONF="generic_views.urls")
WeekArchiveViewTests
python
pytorch__pytorch
test/inductor/test_analysis.py
{ "start": 9476, "end": 23310 }
class ____(TestCase): @skipIf( (not torch.xpu.is_available()) and (not SM80OrLater), "Requires XPU or CUDA SM80", ) def test_noop(self): with ( patch("sys.stdout", new_callable=StringIO) as mock_stdout, patch("sys.argv", [*prefix]), ): main() self.assertEqual(mock_stdout.getvalue(), "") @skipIf( (not torch.xpu.is_available()) and (not SM80OrLater), "Requires XPU or CUDA SM80", ) @dtypes(torch.float, torch.double, torch.float16) def test_diff(self, device, dtype): """ diff, testing out the nruns feature too. """ if device == "cpu" or torch.version.hip is not None: # TODO cpu support return om = _test_model(device, dtype) REPEAT = 5 trace1, trace2 = trace_files() print(f"first trace {trace1}") torch._dynamo.reset() # reset the cache with fresh_inductor_cache(): with torch.profiler.profile(record_shapes=True) as p: om() p.export_chrome_trace(trace1) print(f"second trace {trace2}") torch._dynamo.reset() # reset the cache with fresh_inductor_cache(): with torch.profiler.profile(record_shapes=True) as p: for _ in range(REPEAT): om() p.export_chrome_trace(trace2) print("diffing...") with patch( "sys.argv", [ *prefix, "--diff", trace1, "foo", trace2, "bar", str(dtype).split(".")[-1], "--name_limit", "30", ], ): main() @skipIf(not SM80OrLater, "Requires SM80") def test_augment_trace_helper_unit(self): js = json.loads(example_profile) out_profile = _augment_trace_helper(js) expected_flops = [4096000, 4096000, 223552896, 223552896, 0, 0, 0] verify_flops(self, expected_flops, out_profile) @skipIf( (not torch.xpu.is_available()) and (not SM80OrLater), "Requires XPU or CUDA SM80", ) @skipXPUIf(TEST_WITH_SLOW, "Skip because test too slow on XPU") @dtypes(torch.float, torch.double, torch.float16) @parametrize( "maxat", [ (True, "TRITON"), ], ) @skipIf(not IS_BIG_GPU, "we can't use Triton only as a backend for max autotune") @torch._inductor.config.patch(force_disable_caches=True) def test_triton_has_metadata(self, device, dtype, maxat): """ make sure that the chrome trace of triton kernels contains certain values """ if device == "cpu" or torch.version.hip is not None: return T = cT(device, dtype) input_conv = T(1, 3, 56, 56) conv_weight = T(12, 3, 5, 5) def om(i, w): # Convolution operation conv_output = F.conv2d(i, w) return conv_output max_autotune, backends = maxat comp_omni = torch.compile( om, options={ "benchmark_kernel": True, "max_autotune_gemm_backends": backends, "max_autotune": max_autotune, }, ) def verify_triton(comp): torch._dynamo.reset() # reset the cache with fresh_inductor_cache(): with torch.profiler.profile(record_shapes=True) as profile: comp(input_conv, conv_weight) trace1, _ = trace_files() profile.export_chrome_trace(trace1) with open(trace1) as f: out_profile = json.load(f) seen = False for event in out_profile["traceEvents"]: if "triton" in event["name"] and "conv" in event["name"]: seen = True self.assertTrue(seen, "no triton conv found") verify_triton(comp_omni) @skipIf( (not torch.xpu.is_available()) and (not SM80OrLater), "Requires XPU or CUDA SM80", ) @skipIfXpu( msg="Intel triton issue: https://github.com/intel/intel-xpu-backend-for-triton/issues/5491" ) @skipXPUIf(TEST_WITH_SLOW, "Skip because test too slow on XPU") @dtypes(torch.float, torch.float16) @parametrize( "maxat", [ (False, "ATEN,TRITON"), (True, "ATEN,TRITON"), (True, "ATEN"), (True, "TRITON"), ], ) @unittest.skipIf( not IS_BIG_GPU, "we can't use Triton only as a backend for max autotune" ) @torch._inductor.config.patch(force_disable_caches=True) def test_augment_trace_against_flop_counter(self, device, dtype, maxat): # this tests to see if we can only use a Triton backend for max autotune max_autotune, backends = maxat if device == "cpu" or torch.version.hip is not None: return om = _test_model(device, dtype, compile=False) comp_omni = torch.compile( om, options={ "benchmark_kernel": True, "max_autotune_gemm_backends": backends, "max_autotune": max_autotune, }, ) comp_omni() torch._dynamo.reset() # reset the cache with fresh_inductor_cache(): with torch.profiler.profile(record_shapes=True) as profile: comp_omni() torch._dynamo.reset() # reset the cache with fresh_inductor_cache(): with FlopCounterMode() as mode: comp_omni() trace1, trace2 = trace_files() profile.export_chrome_trace(trace1) with patch( "sys.argv", [*prefix, "--augment_trace", trace1, trace2, str(dtype).split(".")[-1]], ): main() with open(trace2) as f: out_profile = json.load(f) flop_counts = mode.flop_counts extern_mapping = _create_extern_mapping(out_profile) seen_mm = False seen_bmm = False seen_baddbmm = False seen_conv = False for event in out_profile["traceEvents"]: if ( "cat" not in event or event["cat"] != "kernel" or "args" not in event or "External id" not in event["args"] ): continue external_op = extern_mapping[event["args"]["External id"]][0] name: str = external_op["name"] self.assertNotEqual(name, None) self.assertEqual(type(name), str) if name.startswith("aten::mm") or "_mm_" in name: seen_mm = True self.assertEqual( event["args"]["kernel_flop"], flop_counts["Global"][torch.ops.aten.mm], ) if ( name.startswith( ( "aten::cudnn_convolution", "aten::convolution", "aten::_convolution", "aten::convolution_overrideable", ) ) or "conv" in name ): seen_conv = True self.assertEqual( event["args"]["kernel_flop"], flop_counts["Global"][torch.ops.aten.convolution], ) if name.startswith("aten::baddbmm") or "_baddbmm_" in name: seen_baddbmm = True self.assertEqual( event["args"]["kernel_flop"], flop_counts["Global"][torch.ops.aten.baddbmm], ) if name.startswith("aten::bmm") or "_bmm_" in name: seen_bmm = True self.assertEqual( event["args"]["kernel_flop"], flop_counts["Global"][torch.ops.aten.bmm], ) self.assertTrue(seen_mm) self.assertTrue(seen_bmm) self.assertTrue(seen_baddbmm) self.assertTrue(seen_conv) @skipIf( (not torch.xpu.is_available()) and (not SM80OrLater), "Requires XPU or CUDA SM80", ) @skipXPUIf(TEST_WITH_SLOW, "Skip because test too slow on XPU") @dtypes(torch.float, torch.float16) @parametrize( "maxat", [ (False, "ATEN,TRITON"), (True, "ATEN,TRITON"), (True, "ATEN"), (True, "TRITON"), ], ) @unittest.skipIf( not IS_BIG_GPU, "we can't use Triton only as a backend for max autotune" ) @torch._inductor.config.patch(force_disable_caches=True) def test_pointwise_bandwidth(self, device, dtype, maxat): # this tests to see if we can only use a Triton backend for max autotune max_autotune, backends = maxat if device == "cpu" or torch.version.hip is not None: return om = _pointwise_test_model(device, dtype, compile=False) comp_omni = torch.compile( om, options={ "benchmark_kernel": True, "max_autotune_gemm_backends": backends, "max_autotune": max_autotune, }, ) comp_omni() with fresh_inductor_cache(): with torch.profiler.profile(record_shapes=True) as profile: comp_omni() trace1, _ = trace_files() profile.export_chrome_trace(trace1) with patch( "sys.argv", [*prefix, "--analysis", trace1, str(dtype).split(".")[-1]], ): main() with open(trace1) as f: out_profile = json.load(f) for event in out_profile["traceEvents"]: if event["name"] == "triton_poi_fused_add_randn_sin_0": event["args"]["kernel_num_gb"] = 0.002097168 @skipIf( (not torch.xpu.is_available()) and (not SM80OrLater), "Requires XPU or CUDA SM80", ) @dtypes(torch.float, torch.float16) def test_combine_profiles(self, device, dtype): """ Test combining multiple profiles into a single profile. """ if device == "cpu" or torch.version.hip is not None: return # Create three different models to generate different traces om1 = _test_model(device, dtype, addmm=True, bmm=False) om2 = _test_model(device, dtype, addmm=False, bmm=True) om3 = _pointwise_test_model(device, dtype) # Generate three separate traces trace1, trace2 = trace_files() trace3 = f"{TMP_DIR}/trace3-{uuid.uuid4()}.json" combined_trace = f"{TMP_DIR}/combined-{uuid.uuid4()}.json" # Generate first trace torch._dynamo.reset() with fresh_inductor_cache(): with torch.profiler.profile(record_shapes=True) as p1: om1() p1.export_chrome_trace(trace1) # Generate second trace torch._dynamo.reset() with fresh_inductor_cache(): with torch.profiler.profile(record_shapes=True) as p2: om2() p2.export_chrome_trace(trace2) # Generate third trace torch._dynamo.reset() with fresh_inductor_cache(): with torch.profiler.profile(record_shapes=True) as p3: om3() p3.export_chrome_trace(trace3) # Combine the three traces with patch( "sys.argv", [ *prefix, "--combine", trace1, trace2, trace3, combined_trace, ], ): main() # Verify the combined trace exists and contains expected data with open(combined_trace) as f: combined_profile = json.load(f) # Load original traces for comparison with open(trace1) as f: profile1 = json.load(f) with open(trace2) as f: profile2 = json.load(f) with open(trace3) as f: profile3 = json.load(f) # Verify trace events are combined expected_event_count = ( len(profile1["traceEvents"]) + len(profile2["traceEvents"]) + len(profile3["traceEvents"]) ) self.assertEqual(len(combined_profile["traceEvents"]), expected_event_count) # Verify device properties are present self.assertIn("deviceProperties", combined_profile) # XPU currently does not have the deviceProperties like CUDA. # See https://github.com/intel/torch-xpu-ops/issues/2247 if torch.cuda.is_available(): self.assertGreater(len(combined_profile["deviceProperties"]), 0) # Verify some trace events from each original profile are present combined_event_names = { event["name"] for event in combined_profile["traceEvents"] } # Check that we have events from each original profile profile1_event_names = {event["name"] for event in profile1["traceEvents"]} profile2_event_names = {event["name"] for event in profile2["traceEvents"]} profile3_event_names = {event["name"] for event in profile3["traceEvents"]} # At least some events from each profile should be in the combined profile self.assertTrue(profile1_event_names.intersection(combined_event_names)) self.assertTrue(profile2_event_names.intersection(combined_event_names)) self.assertTrue(profile3_event_names.intersection(combined_event_names)) instantiate_device_type_tests(TestAnalysis, globals(), allow_xpu=True) if __name__ == "__main__": run_tests()
TestAnalysis
python
tornadoweb__tornado
tornado/test/iostream_test.py
{ "start": 34924, "end": 35738 }
class ____(TestIOStreamMixin): def _make_server_iostream(self, connection, **kwargs): context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) context.load_cert_chain( os.path.join(os.path.dirname(__file__), "test.crt"), os.path.join(os.path.dirname(__file__), "test.key"), ) connection = ssl_wrap_socket( connection, context, server_side=True, do_handshake_on_connect=False ) return SSLIOStream(connection, **kwargs) def _make_client_iostream(self, connection, **kwargs): context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH) context.check_hostname = False context.verify_mode = ssl.CERT_NONE return SSLIOStream(connection, ssl_options=context, **kwargs)
TestIOStreamSSLContext
python
tensorflow__tensorflow
tensorflow/python/data/kernel_tests/repeat_test.py
{ "start": 1400, "end": 3568 }
class ____(test_base.DatasetTestBase, parameterized.TestCase): @combinations.generate( combinations.times(test_base.default_test_combinations(), combinations.combine(count=[0, 3, 7]))) def testFiniteRepeat(self, count): """Test a dataset that repeats its input multiple times.""" components = (np.array(1), np.array([1, 2, 3]), np.array(37.0)) dataset = dataset_ops.Dataset.from_tensors(components).repeat(count) self.assertEqual( [c.shape for c in components], [shape for shape in dataset_ops.get_legacy_output_shapes(dataset)]) self.assertDatasetProduces(dataset, [components] * count) @combinations.generate(test_base.default_test_combinations()) def testInfiniteRepeat(self): # NOTE(mrry): There's not a good way to test that the sequence is infinite. components = (np.array(1), np.array([1, 2, 3]), np.array(37.0)) dataset = dataset_ops.Dataset.from_tensors(components).repeat(-1) self.assertEqual( [c.shape for c in components], [shape for shape in dataset_ops.get_legacy_output_shapes(dataset)]) get_next = self.getNext(dataset) for _ in range(17): results = self.evaluate(get_next()) for component, result_component in zip(components, results): self.assertAllEqual(component, result_component) @combinations.generate(test_base.default_test_combinations()) def testRepeatRepeat(self): """Test the composition of repeat datasets.""" components = (np.array(1), np.array([1, 2, 3]), np.array(37.0)) inner_count, outer_count = 7, 14 dataset = dataset_ops.Dataset.from_tensors(components).repeat( inner_count).repeat(outer_count) self.assertEqual( [c.shape for c in components], [shape for shape in dataset_ops.get_legacy_output_shapes(dataset)]) self.assertDatasetProduces(dataset, [components] * (inner_count * outer_count)) @combinations.generate(test_base.default_test_combinations()) def testName(self): dataset = dataset_ops.Dataset.from_tensors(42).repeat(1, name="repeat") self.assertDatasetProduces(dataset, [42])
RepeatTest
python
pypa__warehouse
tests/unit/macaroons/test_services.py
{ "start": 684, "end": 13015 }
class ____: def test_creation(self): session = pretend.stub() service = services.DatabaseMacaroonService(session) assert service.db is session @pytest.mark.parametrize( ("raw_macaroon", "result"), [ (None, None), ("noprefixhere", None), ("invalid:prefix", None), ("pypi-validprefix", "validprefix"), ], ) def test_extract_raw_macaroon(self, raw_macaroon, result): assert services._extract_raw_macaroon(raw_macaroon) == result def test_find_macaroon_invalid_uuid(self, macaroon_service): assert macaroon_service.find_macaroon("foobar") is None def test_find_macaroon_missing_macaroon(self, macaroon_service): assert macaroon_service.find_macaroon(str(uuid4())) is None def test_find_macaroon(self, user_service, macaroon_service): user = UserFactory.create() _, macaroon = macaroon_service.create_macaroon( "fake location", "fake description", [caveats.RequestUser(user_id=str(user.id))], user_id=user.id, ) dm = macaroon_service.find_macaroon(str(macaroon.id)) assert isinstance(dm, Macaroon) assert macaroon.id == dm.id assert macaroon.user == user def test_find_from_raw(self, user_service, macaroon_service): user = UserFactory.create() serialized, macaroon = macaroon_service.create_macaroon( "fake location", "fake description", [caveats.RequestUser(user_id=str(user.id))], user_id=user.id, ) dm = macaroon_service.find_from_raw(serialized) assert isinstance(dm, Macaroon) assert macaroon.id == dm.id assert macaroon.user == user assert macaroon.additional is None def test_find_from_raw_oidc(self, macaroon_service): publisher = GitHubPublisherFactory.create() claims = {"sha": "somesha", "ref": "someref"} ( serialized, macaroon, ) = macaroon_service.create_macaroon( "fake location", "fake description", [caveats.OIDCPublisher(oidc_publisher_id=str(publisher.id))], oidc_publisher_id=publisher.id, additional=claims, ) dm = macaroon_service.find_from_raw(serialized) assert isinstance(dm, Macaroon) assert macaroon.id == dm.id assert macaroon.oidc_publisher == publisher assert macaroon.additional == claims @pytest.mark.parametrize( "raw_macaroon", [ "pypi-aaaa", # Invalid macaroon # Macaroon properly formatted but not found. # The string is purposedly cut to avoid triggering the github token # disclosure feature that this very function implements. "py" "pi-AgEIcHlwaS5vcmcCJGQ0ZDhhNzA2LTUxYTEtNDg0NC1hNDlmLTEyZDRiYzNkYjZmOQAABi" "D6hJOpYl9jFI4jBPvA8gvV1mSu1Ic3xMHmxA4CSA2w_g", # Macaroon that is malformed and has an invaild (non utf-8) identifier # The string is purposedly cut to avoid triggering the github token # disclosure feature that this very function implements. "py" "pi-MDAwZWxvY2F0aW9uIAowMDM0aWRlbnRpZmllciBhmTAyMWY0YS0xYWQzLTQ3OGEtYjljZi1" "kMDU1NTkyMGYxYzcKMDAwZnNpZ25hdHVyZSAK", ], ) def test_find_from_raw_not_found_or_invalid(self, macaroon_service, raw_macaroon): with pytest.raises(services.InvalidMacaroonError): macaroon_service.find_from_raw(raw_macaroon) def test_find_userid_no_macaroon(self, macaroon_service): assert macaroon_service.find_userid(None) is None def test_find_userid_invalid_macaroon(self, macaroon_service): raw_macaroon = pymacaroons.Macaroon( location="fake location", identifier=str(uuid4()), key=b"fake key", version=pymacaroons.MACAROON_V2, ).serialize() raw_macaroon = f"pypi-{raw_macaroon}" assert macaroon_service.find_userid(raw_macaroon) is None @pytest.mark.parametrize( "raw_macaroon", [ "pypi-thiswillnotdeserialize", # Macaroon that is malformed and has an invaild (non utf-8) identifier # The string is purposedly cut to avoid triggering the github token # disclosure feature that this very function implements. "py" "pi-MDAwZWxvY2F0aW9uIAowMDM0aWRlbnRpZmllciBhmTAyMWY0YS0xYWQzLTQ3OGEtYjljZi1" "kMDU1NTkyMGYxYzcKMDAwZnNpZ25hdHVyZSAK", ], ) def test_find_userid_malformed_macaroon(self, macaroon_service, raw_macaroon): assert macaroon_service.find_userid(raw_macaroon) is None def test_find_userid_valid_macaroon_trailinglinebreak(self, macaroon_service): user = UserFactory.create() raw_macaroon, _ = macaroon_service.create_macaroon( "fake location", "fake description", [caveats.ProjectName(normalized_names=["foo"])], user_id=user.id, ) assert macaroon_service.find_userid(f"{raw_macaroon}\n") is None def test_find_userid_oidc_macaroon(self, macaroon_service): publisher = GitHubPublisherFactory.create() ( raw_macaroon, _, ) = macaroon_service.create_macaroon( "fake location", "fake description", [caveats.OIDCPublisher(oidc_publisher_id=str(publisher.id))], oidc_publisher_id=publisher.id, ) assert macaroon_service.find_userid(raw_macaroon) is None def test_find_userid(self, macaroon_service): user = UserFactory.create() raw_macaroon, _ = macaroon_service.create_macaroon( "fake location", "fake description", [caveats.RequestUser(user_id=str(user.id))], user_id=user.id, ) user_id = macaroon_service.find_userid(raw_macaroon) assert user.id == user_id def test_verify_unprefixed_macaroon(self, macaroon_service): raw_macaroon = pymacaroons.Macaroon( location="fake location", identifier=str(uuid4()), key=b"fake key", version=pymacaroons.MACAROON_V2, ).serialize() with pytest.raises( services.InvalidMacaroonError, match="malformed or nonexistent macaroon" ): macaroon_service.verify( raw_macaroon, pretend.stub(), pretend.stub(), pretend.stub() ) def test_verify_no_macaroon(self, macaroon_service): raw_macaroon = pymacaroons.Macaroon( location="fake location", identifier=str(uuid4()), key=b"fake key", version=pymacaroons.MACAROON_V2, ).serialize() raw_macaroon = f"pypi-{raw_macaroon}" with pytest.raises( services.InvalidMacaroonError, match="deleted or nonexistent macaroon" ): macaroon_service.verify( raw_macaroon, pretend.stub(), pretend.stub(), pretend.stub() ) def test_verify_invalid_macaroon(self, monkeypatch, user_service, macaroon_service): user = UserFactory.create() raw_macaroon, _ = macaroon_service.create_macaroon( "fake location", "fake description", [caveats.RequestUser(user_id=str(user.id))], user_id=user.id, ) verify = pretend.call_recorder(lambda m, k, r, c, p: WarehouseDenied("foo")) monkeypatch.setattr(caveats, "verify", verify) request = pretend.stub() context = pretend.stub() permissions = pretend.stub() with pytest.raises(services.InvalidMacaroonError, match="foo"): macaroon_service.verify(raw_macaroon, request, context, permissions) assert verify.calls == [ pretend.call(mock.ANY, mock.ANY, request, context, permissions) ] def test_deserialize_raw_macaroon_when_none(self, monkeypatch): raw_macaroon = None _extract_func = pretend.call_recorder(lambda a: raw_macaroon) monkeypatch.setattr(services, "_extract_raw_macaroon", _extract_func) with pytest.raises( services.InvalidMacaroonError, match="malformed or nonexistent macaroon" ): services.deserialize_raw_macaroon(raw_macaroon) assert services._extract_raw_macaroon.calls == [ pretend.call(raw_macaroon), ] @pytest.mark.parametrize( "exception", [ IndexError, TypeError, UnicodeDecodeError, ValueError, binascii.Error, struct.error, MacaroonDeserializationException, Exception, # https://github.com/ecordell/pymacaroons/issues/50 ], ) def test_deserialize_raw_macaroon(self, monkeypatch, exception): raw_macaroon = pretend.stub() monkeypatch.setattr(services, "_extract_raw_macaroon", lambda a: raw_macaroon) monkeypatch.setattr( pymacaroons.Macaroon, "deserialize", pretend.raiser(exception) ) with pytest.raises(services.InvalidMacaroonError): services.deserialize_raw_macaroon(raw_macaroon) def test_verify_malformed_macaroon(self, macaroon_service): with pytest.raises(services.InvalidMacaroonError): macaroon_service.verify("pypi-thiswillnotdeserialize", None, None, None) def test_verify_valid_macaroon(self, monkeypatch, macaroon_service): user = UserFactory.create() raw_macaroon, _ = macaroon_service.create_macaroon( "fake location", "fake description", [caveats.RequestUser(user_id=str(user.id))], user_id=user.id, ) verify = pretend.call_recorder(lambda m, k, r, c, p: True) monkeypatch.setattr(caveats, "verify", verify) request = pretend.stub() context = pretend.stub() permissions = pretend.stub() assert macaroon_service.verify(raw_macaroon, request, context, permissions) assert verify.calls == [ pretend.call(mock.ANY, mock.ANY, request, context, permissions) ] def test_delete_macaroon(self, user_service, macaroon_service): user = UserFactory.create() _, macaroon = macaroon_service.create_macaroon( "fake location", "fake description", [caveats.RequestUser(user_id=str(user.id))], user_id=user.id, ) macaroon_id = str(macaroon.id) macaroon_service.delete_macaroon(macaroon_id) assert macaroon_service.find_macaroon(macaroon_id) is None def test_delete_macaroon_no_macaroon(self, macaroon_service): assert macaroon_service.delete_macaroon("no such macaroon") is None def test_get_macaroon_by_description_no_macaroon(self, macaroon_service): user = UserFactory.create() assert ( macaroon_service.get_macaroon_by_description(user.id, "no such description") is None ) def test_get_macaroon_by_description(self, macaroon_service): user = UserFactory.create() _, macaroon = macaroon_service.create_macaroon( "fake location", "fake description", [ caveats.ProjectName(normalized_names=["foo", "bar"]), caveats.Expiration(expires_at=10, not_before=5), ], user_id=user.id, ) dm = macaroon_service.find_macaroon(str(macaroon.id)) assert ( macaroon_service.get_macaroon_by_description(user.id, macaroon.description) == dm ) def test_errors_with_wrong_caveats(self, macaroon_service): user = UserFactory.create() with pytest.raises( TypeError, match="scopes must be a list of Caveat instances" ): macaroon_service.create_macaroon( "fake location", "fake description", [{"version": 1, "permissions": "user"}], user_id=user.id, )
TestDatabaseMacaroonService
python
streamlit__streamlit
lib/tests/streamlit/elements/selectbox_test.py
{ "start": 1465, "end": 15564 }
class ____(DeltaGeneratorTestCase): """Test ability to marshall selectbox protos.""" def test_just_label(self): """Test that it can be called with no value.""" st.selectbox("the label", ("m", "f")) c = self.get_delta_from_queue().new_element.selectbox assert c.label == "the label" assert ( c.label_visibility.value == LabelVisibilityMessage.LabelVisibilityOptions.VISIBLE ) assert c.default == 0 assert c.HasField("default") assert not c.disabled # Default placeholders are now handled on the frontend side # Backend only passes through custom user-provided placeholders assert not c.accept_new_options def test_just_disabled(self): """Test that it can be called with disabled param.""" st.selectbox("the label", ("m", "f"), disabled=True) c = self.get_delta_from_queue().new_element.selectbox assert c.disabled def test_valid_value(self): """Test that valid value is an int.""" st.selectbox("the label", ("m", "f"), 1) c = self.get_delta_from_queue().new_element.selectbox assert c.label == "the label" assert c.default == 1 def test_none_index(self): """Test that it can be called with None as index value.""" st.selectbox("the label", ("m", "f"), index=None) c = self.get_delta_from_queue().new_element.selectbox assert c.label == "the label" # If a proto property is null is not determined by this value, # but by the check via the HasField method: assert c.default == 0 assert not c.HasField("default") def test_noneType_option(self): """Test NoneType option value.""" current_value = st.selectbox("the label", (None, "selected"), 0) assert current_value is None @parameterized.expand( SHARED_TEST_CASES, ) def test_option_types(self, name: str, input_data: Any, metadata: CaseMetadata): """Test that it supports different types of options.""" st.selectbox("the label", input_data) c = self.get_delta_from_queue().new_element.selectbox assert c.label == "the label" assert c.default == 0 assert {str(item) for item in c.options} == { str(item) for item in metadata.expected_sequence } def test_cast_options_to_string(self): """Test that it casts options to string.""" arg_options = ["some str", 123, None, {}] proto_options = ["some str", "123", "None", "{}"] st.selectbox("the label", arg_options) c = self.get_delta_from_queue().new_element.selectbox assert c.label == "the label" assert c.default == 0 assert c.options == proto_options def test_format_function(self): """Test that it formats options.""" arg_options = [{"name": "john", "height": 180}, {"name": "lisa", "height": 200}] proto_options = ["john", "lisa"] st.selectbox("the label", arg_options, format_func=lambda x: x["name"]) c = self.get_delta_from_queue().new_element.selectbox assert c.label == "the label" assert c.default == 0 assert c.options == proto_options @parameterized.expand([((),), ([],), (np.array([]),), (pd.Series(np.array([])),)]) def test_no_options(self, options): """Test that it handles no options.""" st.selectbox("the label", options) c = self.get_delta_from_queue().new_element.selectbox assert c.label == "the label" assert c.default == 0 assert c.options == [] def test_accept_new_options(self): """Test that it can accept new options.""" st.selectbox("the label", ("m", "f"), accept_new_options=True) c = self.get_delta_from_queue().new_element.selectbox assert c.accept_new_options # Placeholder logic is now handled on the frontend side # Backend only passes through custom user-provided placeholders def test_invalid_value(self): """Test that value must be an int.""" with pytest.raises(StreamlitAPIException): st.selectbox("the label", ("m", "f"), "1") def test_invalid_value_range(self): """Test that value must be within the length of the options.""" with pytest.raises(StreamlitAPIException): st.selectbox("the label", ("m", "f"), 2) def test_raises_exception_of_index_larger_than_options(self): """Test that it raises an exception if index is larger than options.""" with pytest.raises(StreamlitAPIException) as ex: st.selectbox("Test box", ["a"], index=1) assert ( str(ex.value) == "Selectbox index must be greater than or equal to 0 and less than the length of options." ) def test_outside_form(self): """Test that form id is marshalled correctly outside of a form.""" st.selectbox("foo", ("bar", "baz")) proto = self.get_delta_from_queue().new_element.color_picker assert proto.form_id == "" @patch("streamlit.runtime.Runtime.exists", MagicMock(return_value=True)) def test_inside_form(self): """Test that form id is marshalled correctly inside of a form.""" with st.form("form"): st.selectbox("foo", ("bar", "baz")) # 2 elements will be created: form block, widget assert len(self.get_all_deltas_from_queue()) == 2 form_proto = self.get_delta_from_queue(0).add_block selectbox_proto = self.get_delta_from_queue(1).new_element.selectbox assert selectbox_proto.form_id == form_proto.form.form_id @parameterized.expand( [ ("visible", LabelVisibilityMessage.LabelVisibilityOptions.VISIBLE), ("hidden", LabelVisibilityMessage.LabelVisibilityOptions.HIDDEN), ("collapsed", LabelVisibilityMessage.LabelVisibilityOptions.COLLAPSED), ] ) def test_label_visibility(self, label_visibility_value, proto_value): """Test that it can be called with label_visibility param.""" st.selectbox("the label", ("m", "f"), label_visibility=label_visibility_value) c = self.get_delta_from_queue().new_element.selectbox assert c.label_visibility.value == proto_value def test_label_visibility_wrong_value(self): with pytest.raises(StreamlitAPIException) as e: st.selectbox("the label", ("m", "f"), label_visibility="wrong_value") assert ( str(e.value) == "Unsupported label_visibility option 'wrong_value'. Valid values are 'visible', 'hidden' or 'collapsed'." ) def test_placeholder(self): """Test that it can be called with placeholder params.""" st.selectbox("the label", ("m", "f"), placeholder="Please select") c = self.get_delta_from_queue().new_element.selectbox assert c.placeholder == "Please select" def test_width_config_default(self): """Test that default width is 'stretch'.""" st.selectbox("the label", ("m", "f")) c = self.get_delta_from_queue().new_element assert ( c.width_config.WhichOneof("width_spec") == WidthConfigFields.USE_STRETCH.value ) assert c.width_config.use_stretch def test_width_config_pixel(self): """Test that pixel width works properly.""" st.selectbox("the label", ("m", "f"), width=200) c = self.get_delta_from_queue().new_element assert ( c.width_config.WhichOneof("width_spec") == WidthConfigFields.PIXEL_WIDTH.value ) assert c.width_config.pixel_width == 200 def test_width_config_stretch(self): """Test that 'stretch' width works properly.""" st.selectbox("the label", ("m", "f"), width="stretch") c = self.get_delta_from_queue().new_element assert ( c.width_config.WhichOneof("width_spec") == WidthConfigFields.USE_STRETCH.value ) assert c.width_config.use_stretch @parameterized.expand( [ "invalid", -100, 0, 100.5, None, ] ) def test_invalid_width(self, width): """Test that invalid width values raise exceptions.""" with pytest.raises(StreamlitInvalidWidthError): st.selectbox("the label", ("m", "f"), width=width) def test_shows_cached_widget_replay_warning(self): """Test that a warning is shown when this widget is used inside a cached function.""" st.cache_data(lambda: st.selectbox("the label", ["Coffee", "Tea", "Water"]))() # The widget itself is still created, so we need to go back one element more: el = self.get_delta_from_queue(-2).new_element.exception assert el.type == "CachedWidgetWarning" assert el.is_warning def test_stable_id_with_key(self): """Test that the widget ID is stable when a stable key is provided.""" with patch( "streamlit.elements.lib.utils._register_element_id", return_value=MagicMock(), ): # First render with certain params st.selectbox( label="Label 1", key="selectbox_key", index=0, help="Help 1", disabled=False, width="stretch", on_change=lambda: None, args=("arg1", "arg2"), kwargs={"kwarg1": "kwarg1"}, label_visibility="visible", placeholder="placeholder 1", # Whitelisted kwargs: format_func=lambda x: x.capitalize(), options=["a", "b", "cd"], accept_new_options=True, ) c1 = self.get_delta_from_queue().new_element.selectbox id1 = c1.id # Second render with different non-whitelisted params but same key st.selectbox( label="Label 2", key="selectbox_key", index=None, help="Help 2", disabled=True, width=200, on_change=lambda: None, args=("arg_1", "arg_2"), kwargs={"kwarg_1": "kwarg_1"}, label_visibility="hidden", placeholder="placeholder 2", # Whitelisted kwargs: format_func=lambda x: x.capitalize(), options=["a", "b", "cd"], accept_new_options=True, ) c2 = self.get_delta_from_queue().new_element.selectbox id2 = c2.id assert id1 == id2 @parameterized.expand( [ ("options", ["a", "b"], ["a", "b", "c"]), ("accept_new_options", True, False), ("format_func", lambda x: x.lower(), lambda x: x.upper()), ] ) def test_whitelisted_stable_key_kwargs( self, kwarg_name: str, value1: object, value2: object ): """Test that the widget ID changes when a whitelisted kwarg changes even when the key is provided.""" with patch( "streamlit.elements.lib.utils._register_element_id", return_value=MagicMock(), ): base_kwargs = { "label": "Label", "key": "selectbox_key_whitelist", "options": ["a", "b"], "accept_new_options": True, "format_func": lambda x: x.lower(), } base_kwargs[kwarg_name] = value1 st.selectbox(**base_kwargs) c1 = self.get_delta_from_queue().new_element.selectbox id1 = c1.id base_kwargs[kwarg_name] = value2 st.selectbox(**base_kwargs) c2 = self.get_delta_from_queue().new_element.selectbox id2 = c2.id assert id1 != id2 def test_selectbox_interaction(): """Test interactions with an empty selectbox widget.""" def script(): import streamlit as st st.selectbox("the label", ("m", "f"), index=None) at = AppTest.from_function(script).run() selectbox = at.selectbox[0] assert selectbox.value is None # Select option m at = selectbox.set_value("m").run() selectbox = at.selectbox[0] assert selectbox.value == "m" # # Clear the value at = selectbox.set_value(None).run() selectbox = at.selectbox[0] assert selectbox.value is None def test_selectbox_enum_coercion(): """Test E2E Enum Coercion on a selectbox.""" def script(): from enum import Enum import streamlit as st class EnumA(Enum): A = 1 B = 2 C = 3 selected = st.selectbox("my_enum", EnumA, index=0) st.text(id(selected.__class__)) st.text(id(EnumA)) st.text(selected in EnumA) at = AppTest.from_function(script).run() def test_enum(): selectbox = at.selectbox[0] original_class = selectbox.value.__class__ selectbox.set_value(original_class.C).run() assert at.text[0].value == at.text[1].value, "Enum Class ID not the same" assert at.text[2].value == "True", "Not all enums found in class" with patch_config_options({"runner.enumCoercion": "nameOnly"}): test_enum() with ( patch_config_options({"runner.enumCoercion": "off"}), pytest.raises(AssertionError), ): test_enum() # expect a failure with the config value off. def test_None_session_state_value_retained(): def script(): import streamlit as st if "selectbox" not in st.session_state: st.session_state["selectbox"] = None st.selectbox("selectbox", ["a", "b", "c"], key="selectbox") st.button("button") at = AppTest.from_function(script).run() at = at.button[0].click().run() assert at.selectbox[0].value is None
SelectboxTest
python
scipy__scipy
scipy/special/tests/test_basic.py
{ "start": 68800, "end": 75363 }
class ____: """Test for Carlson elliptic integrals ellipr[cdfgj]. The special values used in these tests can be found in Sec. 3 of Carlson (1994), https://arxiv.org/abs/math/9409227 """ def test_elliprc(self): assert_allclose(elliprc(1, 1), 1) assert elliprc(1, inf) == 0.0 assert isnan(elliprc(1, 0)) assert elliprc(1, complex(1, inf)) == 0.0 args = array([[0.0, 0.25], [2.25, 2.0], [0.0, 1.0j], [-1.0j, 1.0j], [0.25, -2.0], [1.0j, -1.0]]) expected_results = array([np.pi, np.log(2.0), 1.1107207345396 * (1.0-1.0j), 1.2260849569072-0.34471136988768j, np.log(2.0) / 3.0, 0.77778596920447+0.19832484993429j]) for i, arr in enumerate(args): assert_allclose(elliprc(*arr), expected_results[i]) def test_elliprd(self): assert_allclose(elliprd(1, 1, 1), 1) assert_allclose(elliprd(0, 2, 1) / 3.0, 0.59907011736779610371) assert elliprd(1, 1, inf) == 0.0 assert np.isinf(elliprd(1, 1, 0)) assert np.isinf(elliprd(1, 1, complex(0, 0))) assert np.isinf(elliprd(0, 1, complex(0, 0))) assert isnan(elliprd(1, 1, -np.finfo(np.float64).tiny / 2.0)) assert isnan(elliprd(1, 1, complex(-1, 0))) args = array([[0.0, 2.0, 1.0], [2.0, 3.0, 4.0], [1.0j, -1.0j, 2.0], [0.0, 1.0j, -1.0j], [0.0, -1.0+1.0j, 1.0j], [-2.0-1.0j, -1.0j, -1.0+1.0j]]) expected_results = array([1.7972103521034, 0.16510527294261, 0.65933854154220, 1.2708196271910+2.7811120159521j, -1.8577235439239-0.96193450888839j, 1.8249027393704-1.2218475784827j]) for i, arr in enumerate(args): assert_allclose(elliprd(*arr), expected_results[i]) def test_elliprf(self): assert_allclose(elliprf(1, 1, 1), 1) assert_allclose(elliprf(0, 1, 2), 1.31102877714605990523) assert elliprf(1, inf, 1) == 0.0 assert np.isinf(elliprf(0, 1, 0)) assert isnan(elliprf(1, 1, -1)) assert elliprf(complex(inf), 0, 1) == 0.0 assert isnan(elliprf(1, 1, complex(-inf, 1))) args = array([[1.0, 2.0, 0.0], [1.0j, -1.0j, 0.0], [0.5, 1.0, 0.0], [-1.0+1.0j, 1.0j, 0.0], [2.0, 3.0, 4.0], [1.0j, -1.0j, 2.0], [-1.0+1.0j, 1.0j, 1.0-1.0j]]) expected_results = array([1.3110287771461, 1.8540746773014, 1.8540746773014, 0.79612586584234-1.2138566698365j, 0.58408284167715, 1.0441445654064, 0.93912050218619-0.53296252018635j]) for i, arr in enumerate(args): assert_allclose(elliprf(*arr), expected_results[i]) def test_elliprg(self): assert_allclose(elliprg(1, 1, 1), 1) assert_allclose(elliprg(0, 0, 1), 0.5) assert_allclose(elliprg(0, 0, 0), 0) assert np.isinf(elliprg(1, inf, 1)) assert np.isinf(elliprg(complex(inf), 1, 1)) args = array([[0.0, 16.0, 16.0], [2.0, 3.0, 4.0], [0.0, 1.0j, -1.0j], [-1.0+1.0j, 1.0j, 0.0], [-1.0j, -1.0+1.0j, 1.0j], [0.0, 0.0796, 4.0]]) expected_results = array([np.pi, 1.7255030280692, 0.42360654239699, 0.44660591677018+0.70768352357515j, 0.36023392184473+0.40348623401722j, 1.0284758090288]) for i, arr in enumerate(args): assert_allclose(elliprg(*arr), expected_results[i]) def test_elliprj(self): assert_allclose(elliprj(1, 1, 1, 1), 1) assert elliprj(1, 1, inf, 1) == 0.0 assert isnan(elliprj(1, 0, 0, 0)) assert isnan(elliprj(-1, 1, 1, 1)) assert elliprj(1, 1, 1, inf) == 0.0 args = array([[0.0, 1.0, 2.0, 3.0], [2.0, 3.0, 4.0, 5.0], [2.0, 3.0, 4.0, -1.0+1.0j], [1.0j, -1.0j, 0.0, 2.0], [-1.0+1.0j, -1.0-1.0j, 1.0, 2.0], [1.0j, -1.0j, 0.0, 1.0-1.0j], [-1.0+1.0j, -1.0-1.0j, 1.0, -3.0+1.0j], [2.0, 3.0, 4.0, -0.5], # Cauchy principal value [2.0, 3.0, 4.0, -5.0]]) # Cauchy principal value expected_results = array([0.77688623778582, 0.14297579667157, 0.13613945827771-0.38207561624427j, 1.6490011662711, 0.94148358841220, 1.8260115229009+1.2290661908643j, -0.61127970812028-1.0684038390007j, 0.24723819703052, # Cauchy principal value -0.12711230042964]) # Caucny principal value for i, arr in enumerate(args): assert_allclose(elliprj(*arr), expected_results[i]) @pytest.mark.xfail(reason="Insufficient accuracy on 32-bit") def test_elliprj_hard(self): assert_allclose(elliprj(6.483625725195452e-08, 1.1649136528196886e-27, 3.6767340167168e+13, 0.493704617023468), 8.63426920644241857617477551054e-6, rtol=5e-15, atol=1e-20) assert_allclose(elliprj(14.375105857849121, 9.993988969725365e-11, 1.72844262269944e-26, 5.898871222598245e-06), 829774.1424801627252574054378691828, rtol=5e-15, atol=1e-20)
TestEllipCarlson
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/dialects/mssql/base.py
{ "start": 39602, "end": 41011 }
class ____(sqltypes.TIME): def __init__(self, precision=None, **kwargs): self.precision = precision super().__init__() __zero_date = datetime.date(1900, 1, 1) def bind_processor(self, dialect): def process(value): if isinstance(value, datetime.datetime): value = datetime.datetime.combine( self.__zero_date, value.time() ) elif isinstance(value, datetime.time): """issue #5339 per: https://github.com/mkleehammer/pyodbc/wiki/Tips-and-Tricks-by-Database-Platform#time-columns pass TIME value as string """ # noqa value = str(value) return value return process _reg = re.compile(r"(\d+):(\d+):(\d+)(?:\.(\d{0,6}))?") def result_processor(self, dialect, coltype): def process(value): if isinstance(value, datetime.datetime): return value.time() elif isinstance(value, str): m = self._reg.match(value) if not m: raise ValueError( "could not parse %r as a time value" % (value,) ) return datetime.time(*[int(x or 0) for x in m.groups()]) else: return value return process _MSTime = TIME
TIME
python
sympy__sympy
sympy/tensor/array/expressions/array_expressions.py
{ "start": 36629, "end": 37634 }
class ____(_CodegenArrayAbstract): def __new__(cls, function, element): if not isinstance(function, Lambda): d = Dummy('d') function = Lambda(d, function(d)) obj = _CodegenArrayAbstract.__new__(cls, function, element) obj._subranks = _get_subranks(element) return obj @property def function(self): return self.args[0] @property def expr(self): return self.args[1] @property def shape(self): return get_shape(self.expr) def _get_function_fdiff(self): d = Dummy("d") function = self.function(d) fdiff = function.diff(d) if isinstance(fdiff, Function): fdiff = type(fdiff) else: fdiff = Lambda(d, fdiff) return fdiff def as_explicit(self): expr = self.expr if hasattr(expr, "as_explicit"): expr = expr.as_explicit() return expr.applyfunc(self.function)
ArrayElementwiseApplyFunc
python
spack__spack
lib/spack/spack/solver/core.py
{ "start": 850, "end": 1452 }
class ____: """Object representing a piece of ASP code.""" def _id(thing: Any) -> Union[str, int, AspObject]: """Quote string if needed for it to be a valid identifier.""" if thing is True or thing is False: return f'"{thing}"' elif isinstance(thing, (AspObject, int)): return thing else: if isinstance(thing, str): # escape characters that cannot be in clingo strings thing = thing.replace("\\", r"\\") thing = thing.replace("\n", r"\n") thing = thing.replace('"', r"\"") return f'"{thing}"'
AspObject
python
scipy__scipy
benchmarks/benchmarks/go_benchmark_functions/go_funcs_Z.py
{ "start": 3768, "end": 5643 }
class ____(Benchmark): r""" Zimmerman objective function. This class defines the Zimmerman [1]_ global optimization problem. This is a multimodal minimization problem defined as follows: .. math:: f_{\text{Zimmerman}}(x) = \max \left[Zh1(x), Zp(Zh2(x)) \textrm{sgn}(Zh2(x)), Zp(Zh3(x)) \textrm{sgn}(Zh3(x)), Zp(-x_1)\textrm{sgn}(x_1), Zp(-x_2)\textrm{sgn}(x_2) \right] Where, in this exercise: .. math:: \begin{cases} Zh1(x) = 9 - x_1 - x_2 \\ Zh2(x) = (x_1 - 3)^2 + (x_2 - 2)^2 \\ Zh3(x) = x_1x_2 - 14 \\ Zp(t) = 100(1 + t) \end{cases} Where :math:`x` is a vector and :math:`t` is a scalar. Here, :math:`x_i \in [0, 100]` for :math:`i = 1, 2`. *Global optimum*: :math:`f(x) = 0` for :math:`x = [7, 2]` .. [1] Gavana, A. Global Optimization Benchmarks and AMPGO retrieved 2015 TODO implementation from Gavana """ def __init__(self, dimensions=2): Benchmark.__init__(self, dimensions) self._bounds = list(zip([0.0] * self.N, [100.0] * self.N)) self.custom_bounds = ([0.0, 8.0], [0.0, 8.0]) self.global_optimum = [[7.0, 2.0]] self.fglob = 0.0 def fun(self, x, *args): def Zh1(x): return 9.0 - x[0] - x[1] def Zh2(x): return (x[0] - 3.0) ** 2.0 + (x[1] - 2.0) ** 2.0 - 16.0 def Zh3(x): return x[0] * x[1] - 14.0 def Zp(x): return 100.0 * (1.0 + x) self.nfev += 1 return max(Zh1(x), Zp(Zh2(x)) * sign(Zh2(x)), Zp(Zh3(x)) * sign(Zh3(x)), Zp(-x[0]) * sign(x[0]), Zp(-x[1]) * sign(x[1]))
Zimmerman
python
huggingface__transformers
src/transformers/models/dinov2/modeling_dinov2.py
{ "start": 20279, "end": 22268 }
class ____(Dinov2PreTrainedModel): def __init__(self, config: Dinov2Config) -> None: super().__init__(config) self.num_labels = config.num_labels self.dinov2 = Dinov2Model(config) # Classifier head self.classifier = ( nn.Linear(config.hidden_size * 2, config.num_labels) if config.num_labels > 0 else nn.Identity() ) # Initialize weights and apply final processing self.post_init() @can_return_tuple @auto_docstring def forward( self, pixel_values: Optional[torch.Tensor] = None, labels: Optional[torch.Tensor] = None, **kwargs: Unpack[TransformersKwargs], ) -> ImageClassifierOutput: r""" labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): Labels for computing the image classification/regression loss. Indices should be in `[0, ..., config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If `config.num_labels > 1` a classification loss is computed (Cross-Entropy). """ outputs: BaseModelOutputWithPooling = self.dinov2(pixel_values, **kwargs) sequence_output = outputs.last_hidden_state # batch_size, sequence_length, hidden_size cls_token = sequence_output[:, 0] patch_tokens = sequence_output[:, 1:] linear_input = torch.cat([cls_token, patch_tokens.mean(dim=1)], dim=1) logits = self.classifier(linear_input) loss = None if labels is not None: loss = self.loss_function(labels, logits, self.config, **kwargs) return ImageClassifierOutput( loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions, ) @auto_docstring( custom_intro=""" Dinov2 backbone, to be used with frameworks like DETR and MaskFormer. """ )
Dinov2ForImageClassification
python
django__django
tests/foreign_object/models/person.py
{ "start": 1077, "end": 2081 }
class ____(models.Model): # Table Column Fields membership_country = models.ForeignKey(Country, models.CASCADE, null=True) date_joined = models.DateTimeField(default=datetime.datetime.now) invite_reason = models.CharField(max_length=64, null=True) person_id = models.IntegerField() group_id = models.IntegerField(blank=True, null=True) # Relation Fields person = models.ForeignObject( Person, from_fields=["person_id", "membership_country"], to_fields=["id", "person_country_id"], on_delete=models.CASCADE, ) group = models.ForeignObject( Group, from_fields=["group_id", "membership_country"], to_fields=["id", "group_country"], on_delete=models.CASCADE, ) class Meta: ordering = ("date_joined", "invite_reason") def __str__(self): group_name = self.group.name if self.group_id else "NULL" return "%s is a member of %s" % (self.person.name, group_name)
Membership
python
getsentry__sentry
src/sentry/workflow_engine/endpoints/organization_test_fire_action.py
{ "start": 1962, "end": 5325 }
class ____(OrganizationEndpoint): publish_status = { "POST": ApiPublishStatus.EXPERIMENTAL, } owner = ApiOwner.ECOSYSTEM permission_classes = (OrganizationWorkflowPermission,) @extend_schema( operation_id="Test Fire Actions", parameters=[ GlobalParams.ORG_ID_OR_SLUG, ], responses={ 200: None, 400: TestFireActionErrorsResponse, 401: RESPONSE_UNAUTHORIZED, 404: RESPONSE_NOT_FOUND, }, ) def post(self, request: Request, organization) -> Response: """ Test fires a list of actions without saving them to the database. The actions will be fired against a sample event in the first project of the organization. """ serializer = TestActionsValidator(data=request.data, context={"organization": organization}) if not serializer.is_valid(): return Response(serializer.errors, status=HTTP_400_BAD_REQUEST) data = serializer.validated_data if not request.user.is_authenticated: return Response(status=HTTP_401_UNAUTHORIZED) # Get the alphabetically first project associated with the organization # This is because we don't have a project when test firing actions project = ( Project.objects.filter( organization=organization, teams__organizationmember__user_id=request.user.id, status=ObjectStatus.ACTIVE, ) .order_by("name") .first() ) if not project: return Response( {"detail": "No projects found for this organization that the user has access to"}, status=HTTP_400_BAD_REQUEST, ) status, response_data = test_fire_actions(data.get("actions", []), project) return Response(status=status, data=response_data) def test_fire_actions(actions: list[dict[str, Any]], project: Project): action_exceptions = [] test_event = get_test_notification_event_data(project) if test_event is None: # This can happen if the user is rate limited return HTTP_400_BAD_REQUEST, {"detail": "No test event was generated"} workflow_id = TEST_NOTIFICATION_ID workflow_event_data = WorkflowEventData( event=test_event, group=test_event.group, ) for action_data in actions: # Create a temporary Action object (not saved to database) action = Action( id=TEST_NOTIFICATION_ID, type=action_data["type"], integration_id=action_data.get("integration_id"), data=action_data.get("data", {}), config=action_data.get("config", {}), ) # Annotate the action with the workflow id setattr(action, "workflow_id", workflow_id) # Test fire the action and collect any exceptions exceptions = test_fire_action(action, workflow_event_data) if exceptions: action_exceptions.extend(exceptions) # Return any exceptions that occurred status = None response_data = None if len(action_exceptions) > 0: status = HTTP_400_BAD_REQUEST response_data = {"actions": action_exceptions} return status, response_data
OrganizationTestFireActionsEndpoint
python
allegroai__clearml
clearml/backend_api/services/v2_20/models.py
{ "start": 39121, "end": 40652 }
class ____(Response): """ Response of models.create endpoint. :param id: ID of the model :type id: str :param created: Was the model created :type created: bool """ _service = "models" _action = "create" _version = "2.20" _schema = { "definitions": {}, "properties": { "created": { "description": "Was the model created", "type": ["boolean", "null"], }, "id": {"description": "ID of the model", "type": ["string", "null"]}, }, "type": "object", } def __init__(self, id: Optional[str] = None, created: Optional[bool] = None, **kwargs: Any) -> None: super(CreateResponse, self).__init__(**kwargs) self.id = id self.created = created @schema_property("id") def id(self) -> Optional[str]: return self._property_id @id.setter def id(self, value: Optional[str]) -> None: if value is None: self._property_id = None return self.assert_isinstance(value, "id", six.string_types) self._property_id = value @schema_property("created") def created(self) -> Optional[bool]: return self._property_created @created.setter def created(self, value: Optional[bool]) -> None: if value is None: self._property_created = None return self.assert_isinstance(value, "created", (bool,)) self._property_created = value
CreateResponse
python
ray-project__ray
rllib/models/tf/tf_action_dist.py
{ "start": 12272, "end": 14745 }
class ____(TFActionDistribution): """Action distribution where each vector element is a gaussian. The first half of the input vector defines the gaussian means, and the second half the gaussian standard deviations. """ def __init__( self, inputs: List[TensorType], model: ModelV2, *, action_space: Optional[gym.spaces.Space] = None ): mean, log_std = tf.split(inputs, 2, axis=1) self.mean = mean self.log_std = log_std self.std = tf.exp(log_std) # Remember to squeeze action samples in case action space is Box(shape) self.zero_action_dim = action_space and action_space.shape == () super().__init__(inputs, model) @override(ActionDistribution) def deterministic_sample(self) -> TensorType: return self.mean @override(ActionDistribution) def logp(self, x: TensorType) -> TensorType: # Cover case where action space is Box(shape=()). if int(tf.shape(x).shape[0]) == 1: x = tf.expand_dims(x, axis=1) return ( -0.5 * tf.reduce_sum( tf.math.square((tf.cast(x, tf.float32) - self.mean) / self.std), axis=1 ) - 0.5 * np.log(2.0 * np.pi) * tf.cast(tf.shape(x)[1], tf.float32) - tf.reduce_sum(self.log_std, axis=1) ) @override(ActionDistribution) def kl(self, other: ActionDistribution) -> TensorType: assert isinstance(other, DiagGaussian) return tf.reduce_sum( other.log_std - self.log_std + (tf.math.square(self.std) + tf.math.square(self.mean - other.mean)) / (2.0 * tf.math.square(other.std)) - 0.5, axis=1, ) @override(ActionDistribution) def entropy(self) -> TensorType: return tf.reduce_sum(self.log_std + 0.5 * np.log(2.0 * np.pi * np.e), axis=1) @override(TFActionDistribution) def _build_sample_op(self) -> TensorType: sample = self.mean + self.std * tf.random.normal(tf.shape(self.mean)) if self.zero_action_dim: return tf.squeeze(sample, axis=-1) return sample @staticmethod @override(ActionDistribution) def required_model_output_shape( action_space: gym.Space, model_config: ModelConfigDict ) -> Union[int, np.ndarray]: return np.prod(action_space.shape, dtype=np.int32) * 2 @OldAPIStack
DiagGaussian
python
PrefectHQ__prefect
src/prefect/cli/transfer/_migratable_resources/work_queues.py
{ "start": 684, "end": 4500 }
class ____(MigratableResource[WorkQueue]): _instances: dict[uuid.UUID, Self] = {} def __init__(self, work_queue: WorkQueue): self.source_work_queue = work_queue self.destination_work_queue: WorkQueue | None = None self._dependencies: list[MigratableProtocol] = [] @property def source_id(self) -> uuid.UUID: return self.source_work_queue.id @property def destination_id(self) -> uuid.UUID | None: return self.destination_work_queue.id if self.destination_work_queue else None @classmethod async def construct(cls, obj: WorkQueue) -> Self: if obj.id in cls._instances: return cls._instances[obj.id] instance = cls(obj) cls._instances[obj.id] = instance return instance @classmethod async def get_instance( cls, id: uuid.UUID ) -> "MigratableResource[WorkQueue] | None": if id in cls._instances: return cls._instances[id] return None async def get_dependencies(self) -> "list[MigratableProtocol]": if self._dependencies: return self._dependencies async with get_client() as client: if self.source_work_queue.work_pool_name is not None: if dependency := await MigratableWorkPool.get_instance_by_name( name=self.source_work_queue.work_pool_name ): # Always include the pool as a dependency # If it's push/managed, it will be skipped and this queue will be skipped too self._dependencies.append(dependency) else: work_pool = await client.read_work_pool( self.source_work_queue.work_pool_name ) self._dependencies.append( await construct_migratable_resource(work_pool) ) return self._dependencies async def migrate(self) -> None: async with get_client() as client: # Skip default work queues as they are created when work pools are transferred if self.source_work_queue.name == "default": work_queues = await client.read_work_queues( work_pool_name=self.source_work_queue.work_pool_name, work_queue_filter=WorkQueueFilter( name=WorkQueueFilterName(any_=["default"]), ), ) raise TransferSkipped("Default work queues are created with work pools") try: self.destination_work_queue = await client.create_work_queue( name=self.source_work_queue.name, description=self.source_work_queue.description, priority=self.source_work_queue.priority, concurrency_limit=self.source_work_queue.concurrency_limit, work_pool_name=self.source_work_queue.work_pool_name, ) except ObjectAlreadyExists: # Work queue already exists, read it by work pool and name work_queues = await client.read_work_queues( work_pool_name=self.source_work_queue.work_pool_name, work_queue_filter=WorkQueueFilter( name=WorkQueueFilterName(any_=[self.source_work_queue.name]), ), ) if work_queues: self.destination_work_queue = work_queues[0] raise TransferSkipped("Already exists") else: raise RuntimeError( "Transfer failed due to conflict, but no existing queue found." )
MigratableWorkQueue
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/enum4.py
{ "start": 63, "end": 326 }
class ____(enum.Flag): A = enum.auto() B = enum.auto() C = A | B flags1 = CustomFlags.A | CustomFlags.B reveal_type(flags1, expected_text="CustomFlags") flags2 = CustomFlags.A & CustomFlags.B reveal_type(flags2, expected_text="CustomFlags")
CustomFlags
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 174020, "end": 174451 }
class ____(sgqlc.types.Input): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("id", "body", "client_mutation_id") id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="id") body = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="body") client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
UpdateIssueCommentInput
python
getsentry__sentry
src/sentry/release_health/metrics_sessions_v2.py
{ "start": 11283, "end": 12319 }
class ____(Field): def __init__(self, name: str, raw_groupby: Sequence[str], status_filter: StatusFilter): self.op = name[:3] # That this works is just a lucky coincidence super().__init__(name, raw_groupby, status_filter) def _get_session_status(self, metric_field: MetricField) -> SessionStatus | None: assert metric_field == MetricField(self.op, SessionMRI.DURATION.value) if "session.status" in self._raw_groupby: return SessionStatus.HEALTHY return None def _get_metric_fields( self, raw_groupby: Sequence[str], status_filter: StatusFilter ) -> Sequence[MetricField]: if status_filter is None or SessionStatus.HEALTHY in status_filter: return [MetricField(self.op, SessionMRI.DURATION.value)] return [] # TODO: test if we can handle zero fields def normalize(self, value: Scalar) -> Scalar: value = finite_or_none(value) if value is not None: value *= 1000 return value
DurationField
python
google__jax
jax/_src/debugger/core.py
{ "start": 1365, "end": 2020 }
class ____: __repr__ = lambda _: "<cant_flatten>" cant_flatten = _CantFlatten() def _safe_flatten_dict(dct: dict[Any, Any] ) -> tuple[list[Any], tree_util.PyTreeDef]: # We avoid comparison between keys by just using the original order keys, values = [], [] for key, value in dct.items(): try: tree_util.tree_leaves(value) except: # If flattening fails, we substitute a sentinel object. value = cant_flatten keys.append(key) values.append(value) return tree_util.tree_flatten(_DictWrapper(keys, values)) @tree_util.register_pytree_node_class @dataclasses.dataclass(frozen=True)
_CantFlatten
python
zarr-developers__zarr-python
src/zarr/errors.py
{ "start": 461, "end": 1020 }
class ____(ValueError): """ Base error which all zarr errors are sub-classed from. """ _msg: str = "{}" def __init__(self, *args: object) -> None: """ If a single argument is passed, treat it as a pre-formatted message. If multiple arguments are passed, they are used as arguments for a template string class variable. This behavior is deprecated. """ if len(args) == 1: super().__init__(args[0]) else: super().__init__(self._msg.format(*args))
BaseZarrError
python
getsentry__sentry
tests/sentry/api/validators/test_organization_member_invite_validator.py
{ "start": 310, "end": 6182 }
class ____(TestCase): def test_valid(self) -> None: context = { "organization": self.organization, "allowed_roles": [roles.get("member")], "actor": self.user, } data = { "email": "mifu@email.com", "orgRole": "member", "teams": [self.team.slug], } serializer = OrganizationMemberInviteRequestValidator(context=context, data=data) assert serializer.is_valid() assert serializer.validated_data["teams"][0] == self.team def test_member_with_email_exists(self) -> None: org = self.create_organization() user = self.create_user() self.create_member(organization=org, user=user) context = { "organization": org, "allowed_roles": [roles.get("member")], "actor": self.user, } data = {"email": user.email, "orgRole": "member", "teams": []} serializer = OrganizationMemberInviteRequestValidator(context=context, data=data) assert not serializer.is_valid() assert serializer.errors == {"email": [f"The user {user.email} is already a member"]} def test_invite_with_email_exists(self) -> None: email = "mifu@email.com" self.create_member_invite(organization=self.organization, email=email) context = { "organization": self.organization, "allowed_roles": [roles.get("member")], "actor": self.user, } data = {"email": email, "orgRole": "member", "teamRoles": []} serializer = OrganizationMemberInviteRequestValidator(context=context, data=data) assert not serializer.is_valid() assert serializer.errors == {"email": [f"The user {email} has already been invited"]} def test_invalid_team_invites(self) -> None: context = { "organization": self.organization, "allowed_roles": [roles.get("member")], "actor": self.user, } data = {"email": "mifu@email.com", "orgRole": "member", "teams": ["faketeam"]} serializer = OrganizationMemberInviteRequestValidator(context=context, data=data) assert not serializer.is_valid() assert serializer.errors == {"teams": ["Invalid teams"]} def test_invalid_org_role(self) -> None: context = { "organization": self.organization, "allowed_roles": [roles.get("member")], "actor": self.user, } data = {"email": "mifu@email.com", "orgRole": "owner", "teamRoles": []} serializer = OrganizationMemberInviteRequestValidator(context=context, data=data) assert not serializer.is_valid() assert serializer.errors == { "orgRole": ["You do not have permission to invite a member with that org-level role"] } def test_cannot_invite_with_existing_request(self) -> None: email = "test@gmail.com" self.create_member_invite( email=email, organization=self.organization, invite_status=InviteStatus.REQUESTED_TO_BE_INVITED.value, ) context = { "organization": self.organization, "allowed_roles": [roles.get("member")], "actor": self.user, } data = {"email": email, "orgRole": "member", "teams": [self.team.slug]} serializer = OrganizationMemberInviteRequestValidator(context=context, data=data) assert not serializer.is_valid() assert serializer.errors == { "email": ["There is an existing invite request for test@gmail.com"] } @with_feature("organizations:team-roles") def test_deprecated_org_role_with_flag(self) -> None: context = { "organization": self.organization, "allowed_roles": [roles.get("admin"), roles.get("member")], "actor": self.user, } data = {"email": "mifu@email.com", "orgRole": "admin", "teams": []} serializer = OrganizationMemberInviteRequestValidator(context=context, data=data) assert not serializer.is_valid() assert serializer.errors == { "orgRole": [ "The role 'admin' is deprecated, and members may no longer be invited with it." ] } @with_feature({"organizations:team-roles": False}) def test_deprecated_org_role_without_flag(self) -> None: context = { "organization": self.organization, "allowed_roles": [roles.get("admin"), roles.get("member")], "actor": self.user, } data = {"email": "mifu@email.com", "orgRole": "admin", "teams": []} serializer = OrganizationMemberInviteRequestValidator(context=context, data=data) assert serializer.is_valid() @with_feature("organizations:invite-billing") def test_valid_invite_billing_member(self) -> None: context = { "organization": self.organization, "allowed_roles": [roles.get("member")], "actor": self.user, } data = { "email": "bill@localhost", "orgRole": "billing", "teamRoles": [], } serializer = OrganizationMemberInviteRequestValidator(context=context, data=data) assert serializer.is_valid() def test_invalid_invite_billing_member(self) -> None: context = { "organization": self.organization, "allowed_roles": [roles.get("member")], "actor": self.user, } data = { "email": "bill@localhost", "orgRole": "billing", "teamRoles": [], } serializer = OrganizationMemberInviteRequestValidator(context=context, data=data) assert not serializer.is_valid()
OrganizationMemberInviteRequestValidatorTest
python
ray-project__ray
python/ray/tune/tests/_test_trial_runner_callbacks.py
{ "start": 2172, "end": 10042 }
class ____(unittest.TestCase): def setUp(self): ray.init() self.tmpdir = tempfile.mkdtemp() self.callback = TestCallback() self.executor = _MockTrialExecutor() self.trial_runner = TrialRunner( trial_executor=self.executor, callbacks=[self.callback] ) # experiment would never be None normally, but it's fine for testing self.trial_runner.setup_experiments(experiments=[None], total_num_samples=1) def tearDown(self): ray.shutdown() _register_all() # re-register the evicted objects if "CUDA_VISIBLE_DEVICES" in os.environ: del os.environ["CUDA_VISIBLE_DEVICES"] shutil.rmtree(self.tmpdir) def testCallbackSteps(self): trials = [Trial("__fake", trial_id="one"), Trial("__fake", trial_id="two")] for t in trials: self.trial_runner.add_trial(t) self.executor.next_future_result = _ExecutorEvent( event_type=_ExecutorEventType.PG_READY ) self.trial_runner.step() # Trial 1 has been started self.assertEqual(self.callback.state["trial_start"]["iteration"], 0) self.assertEqual(self.callback.state["trial_start"]["trial"].trial_id, "one") # All these events haven't happened, yet self.assertTrue( all( k not in self.callback.state for k in [ "trial_restore", "trial_save", "trial_result", "trial_complete", "trial_fail", "experiment_end", ] ) ) self.executor.next_future_result = _ExecutorEvent( event_type=_ExecutorEventType.PG_READY ) self.trial_runner.step() # Iteration not increased yet self.assertEqual(self.callback.state["step_begin"]["iteration"], 1) # Iteration increased self.assertEqual(self.callback.state["step_end"]["iteration"], 2) # Second trial has been just started self.assertEqual(self.callback.state["trial_start"]["iteration"], 1) self.assertEqual(self.callback.state["trial_start"]["trial"].trial_id, "two") # Just a placeholder object ref for cp.value. cp = _TrackedCheckpoint( dir_or_data=ray.put(1), storage_mode=CheckpointStorage.PERSISTENT, metrics={TRAINING_ITERATION: 0}, ) trials[0].temporary_state.saving_to = cp # Let the first trial save a checkpoint self.executor.next_future_result = _ExecutorEvent( event_type=_ExecutorEventType.SAVING_RESULT, trial=trials[0], result={_ExecutorEvent.KEY_FUTURE_RESULT: "__checkpoint"}, ) self.trial_runner.step() self.assertEqual(self.callback.state["trial_save"]["iteration"], 2) self.assertEqual(self.callback.state["trial_save"]["trial"].trial_id, "one") # Let the second trial send a result result = {TRAINING_ITERATION: 1, "metric": 800, "done": False} self.executor.next_future_result = _ExecutorEvent( event_type=_ExecutorEventType.TRAINING_RESULT, trial=trials[1], result={_ExecutorEvent.KEY_FUTURE_RESULT: result}, ) self.assertTrue(not trials[1].has_reported_at_least_once) self.trial_runner.step() self.assertEqual(self.callback.state["trial_result"]["iteration"], 3) self.assertEqual(self.callback.state["trial_result"]["trial"].trial_id, "two") self.assertEqual(self.callback.state["trial_result"]["result"]["metric"], 800) self.assertEqual(trials[1].last_result["metric"], 800) # Let the second trial restore from a checkpoint trials[1].temporary_state.restoring_from = cp self.executor.next_future_result = _ExecutorEvent( event_type=_ExecutorEventType.RESTORING_RESULT, trial=trials[1], result={_ExecutorEvent.KEY_FUTURE_RESULT: None}, ) self.trial_runner.step() self.assertEqual(self.callback.state["trial_restore"]["iteration"], 4) self.assertEqual(self.callback.state["trial_restore"]["trial"].trial_id, "two") # Let the second trial finish trials[1].temporary_state.restoring_from = None self.executor.next_future_result = _ExecutorEvent( event_type=_ExecutorEventType.TRAINING_RESULT, trial=trials[1], result={ _ExecutorEvent.KEY_FUTURE_RESULT: { TRAINING_ITERATION: 2, "metric": 900, "done": True, } }, ) self.trial_runner.step() self.assertEqual(self.callback.state["trial_complete"]["iteration"], 5) self.assertEqual(self.callback.state["trial_complete"]["trial"].trial_id, "two") # Let the first trial error self.executor.next_future_result = _ExecutorEvent( event_type=_ExecutorEventType.TRAINING_RESULT, trial=trials[0], result={_ExecutorEvent.KEY_EXCEPTION: Exception()}, ) self.trial_runner.step() self.assertEqual(self.callback.state["trial_fail"]["iteration"], 6) self.assertEqual(self.callback.state["trial_fail"]["trial"].trial_id, "one") def testCallbacksEndToEnd(self): def train_fn(config): if config["do"] == "save": with tune.checkpoint_dir(0): pass tune.report(metric=1) elif config["do"] == "fail": raise RuntimeError("I am failing on purpose.") elif config["do"] == "delay": time.sleep(2) tune.report(metric=20) config = {"do": tune.grid_search(["save", "fail", "delay"])} tune.run( train_fn, config=config, raise_on_failed_trial=False, callbacks=[self.callback], ) self.assertIn("setup", self.callback.state) self.assertTrue(self.callback.state["setup"] is not None) keys = Experiment.PUBLIC_KEYS.copy() keys.add("total_num_samples") for key in keys: self.assertIn(key, self.callback.state["setup"]) # check if it was added first self.assertTrue(list(self.callback.state)[0] == "setup") self.assertEqual( self.callback.state["trial_fail"]["trial"].config["do"], "fail" ) self.assertEqual( self.callback.state["trial_save"]["trial"].config["do"], "save" ) self.assertEqual( self.callback.state["trial_result"]["trial"].config["do"], "delay" ) self.assertEqual( self.callback.state["trial_complete"]["trial"].config["do"], "delay" ) self.assertIn("experiment_end", self.callback.state) # check if it was added last self.assertTrue(list(self.callback.state)[-1] == "experiment_end") @patch.object(warnings, "warn") def testCallbackSetupBackwardsCompatible(self, mocked_warning_method): class NoExperimentInSetupCallback(Callback): # Old method definition didn't take in **experiment.public_spec def setup(self): return callback = NoExperimentInSetupCallback() trial_runner = TrialRunner(callbacks=[callback]) trial_runner.setup_experiments( experiments=[Experiment("", lambda x: x)], total_num_samples=1 ) mocked_warning_method.assert_called_once() self.assertIn("Please update", mocked_warning_method.call_args_list[0][0][0]) if __name__ == "__main__": import pytest sys.exit(pytest.main(["-v", __file__]))
TrialRunnerCallbacks
python
scrapy__scrapy
scrapy/commands/edit.py
{ "start": 173, "end": 1358 }
class ____(ScrapyCommand): requires_project = True requires_crawler_process = False default_settings = {"LOG_ENABLED": False} def syntax(self) -> str: return "<spider>" def short_desc(self) -> str: return "Edit spider" def long_desc(self) -> str: return ( "Edit a spider using the editor defined in the EDITOR environment" " variable or else the EDITOR setting" ) def _err(self, msg: str) -> None: sys.stderr.write(msg + os.linesep) self.exitcode = 1 def run(self, args: list[str], opts: argparse.Namespace) -> None: if len(args) != 1: raise UsageError assert self.settings is not None editor = self.settings["EDITOR"] spider_loader = get_spider_loader(self.settings) try: spidercls = spider_loader.load(args[0]) except KeyError: self._err(f"Spider not found: {args[0]}") return sfile = sys.modules[spidercls.__module__].__file__ assert sfile sfile = sfile.replace(".pyc", ".py") self.exitcode = os.system(f'{editor} "{sfile}"') # noqa: S605
Command
python
pytorch__pytorch
torch/profiler/_utils.py
{ "start": 894, "end": 1202 }
class ____: duration_time_ns: int = 0 self_time_ns: int = 0 idle_time_ns: int = 0 queue_depth: int = 0 @property def fraction_idle_time(self): if self.duration_time_ns == 0: return 0.0 return self.idle_time_ns / self.duration_time_ns @dataclass
EventMetrics
python
numpy__numpy
doc/source/conf.py
{ "start": 19808, "end": 21291 }
class ____(CLexer): name = 'NUMPYLEXER' tokens = { 'statements': [ (r'@[a-zA-Z_]*@', Comment.Preproc, 'macro'), inherit, ], } # ----------------------------------------------------------------------------- # Breathe & Doxygen # ----------------------------------------------------------------------------- breathe_projects = {'numpy': os.path.join("..", "build", "doxygen", "xml")} breathe_default_project = "numpy" breathe_default_members = ("members", "undoc-members", "protected-members") # See https://github.com/breathe-doc/breathe/issues/696 nitpick_ignore += [ ('c:identifier', 'FILE'), ('c:identifier', 'size_t'), ('c:identifier', 'PyHeapTypeObject'), ] # ----------------------------------------------------------------------------- # Interactive documentation examples via JupyterLite # ----------------------------------------------------------------------------- global_enable_try_examples = True try_examples_global_button_text = "Try it in your browser!" try_examples_global_warning_text = ( "NumPy's interactive examples are experimental and may not always work" " as expected, with high load times especially on low-resource platforms," " and the version of NumPy might not be in sync with the one you are" " browsing the documentation for. If you encounter any issues, please" " report them on the" " [NumPy issue tracker](https://github.com/numpy/numpy/issues)." )
NumPyLexer
python
giampaolo__psutil
tests/test_process.py
{ "start": 1730, "end": 56728 }
class ____(PsutilTestCase): """Tests for psutil.Process class.""" def test_pid(self): p = psutil.Process() assert p.pid == os.getpid() with pytest.raises(AttributeError): p.pid = 33 def test_kill(self): p = self.spawn_psproc() p.kill() code = p.wait() if WINDOWS: assert code == signal.SIGTERM else: assert code == -signal.SIGKILL self.assert_proc_gone(p) def test_terminate(self): p = self.spawn_psproc() p.terminate() code = p.wait() if WINDOWS: assert code == signal.SIGTERM else: assert code == -signal.SIGTERM self.assert_proc_gone(p) def test_send_signal(self): sig = signal.SIGKILL if POSIX else signal.SIGTERM p = self.spawn_psproc() p.send_signal(sig) code = p.wait() if WINDOWS: assert code == sig else: assert code == -sig self.assert_proc_gone(p) @pytest.mark.skipif(not POSIX, reason="not POSIX") def test_send_signal_mocked(self): sig = signal.SIGTERM p = self.spawn_psproc() with mock.patch('psutil.os.kill', side_effect=ProcessLookupError): with pytest.raises(psutil.NoSuchProcess): p.send_signal(sig) p = self.spawn_psproc() with mock.patch('psutil.os.kill', side_effect=PermissionError): with pytest.raises(psutil.AccessDenied): p.send_signal(sig) def test_wait_exited(self): # Test waitpid() + WIFEXITED -> WEXITSTATUS. # normal return, same as exit(0) cmd = [PYTHON_EXE, "-c", "pass"] p = self.spawn_psproc(cmd) code = p.wait() assert code == 0 self.assert_proc_gone(p) # exit(1), implicit in case of error cmd = [PYTHON_EXE, "-c", "1 / 0"] p = self.spawn_psproc(cmd, stderr=subprocess.PIPE) code = p.wait() assert code == 1 self.assert_proc_gone(p) # via sys.exit() cmd = [PYTHON_EXE, "-c", "import sys; sys.exit(5);"] p = self.spawn_psproc(cmd) code = p.wait() assert code == 5 self.assert_proc_gone(p) # via os._exit() cmd = [PYTHON_EXE, "-c", "import os; os._exit(5);"] p = self.spawn_psproc(cmd) code = p.wait() assert code == 5 self.assert_proc_gone(p) @pytest.mark.skipif(NETBSD, reason="fails on NETBSD") def test_wait_stopped(self): p = self.spawn_psproc() if POSIX: # Test waitpid() + WIFSTOPPED and WIFCONTINUED. # Note: if a process is stopped it ignores SIGTERM. p.send_signal(signal.SIGSTOP) with pytest.raises(psutil.TimeoutExpired): p.wait(timeout=0.001) p.send_signal(signal.SIGCONT) with pytest.raises(psutil.TimeoutExpired): p.wait(timeout=0.001) p.send_signal(signal.SIGTERM) assert p.wait() == -signal.SIGTERM assert p.wait() == -signal.SIGTERM else: p.suspend() with pytest.raises(psutil.TimeoutExpired): p.wait(timeout=0.001) p.resume() with pytest.raises(psutil.TimeoutExpired): p.wait(timeout=0.001) p.terminate() assert p.wait() == signal.SIGTERM assert p.wait() == signal.SIGTERM def test_wait_non_children(self): # Test wait() against a process which is not our direct # child. child, grandchild = self.spawn_children_pair() with pytest.raises(psutil.TimeoutExpired): child.wait(0.01) with pytest.raises(psutil.TimeoutExpired): grandchild.wait(0.01) # We also terminate the direct child otherwise the # grandchild will hang until the parent is gone. child.terminate() grandchild.terminate() child_ret = child.wait() grandchild_ret = grandchild.wait() if POSIX: assert child_ret == -signal.SIGTERM # For processes which are not our children we're supposed # to get None. assert grandchild_ret is None else: assert child_ret == signal.SIGTERM assert child_ret == signal.SIGTERM def test_wait_timeout(self): p = self.spawn_psproc() p.name() with pytest.raises(psutil.TimeoutExpired): p.wait(0.01) with pytest.raises(psutil.TimeoutExpired): p.wait(0) with pytest.raises(ValueError): p.wait(-1) def test_wait_timeout_nonblocking(self): p = self.spawn_psproc() with pytest.raises(psutil.TimeoutExpired): p.wait(0) p.kill() stop_at = time.time() + GLOBAL_TIMEOUT while time.time() < stop_at: try: code = p.wait(0) break except psutil.TimeoutExpired: pass else: return pytest.fail('timeout') if POSIX: assert code == -signal.SIGKILL else: assert code == signal.SIGTERM self.assert_proc_gone(p) def test_cpu_percent(self): p = psutil.Process() p.cpu_percent(interval=0.001) p.cpu_percent(interval=0.001) for _ in range(100): percent = p.cpu_percent(interval=None) assert isinstance(percent, float) assert percent >= 0.0 with pytest.raises(ValueError): p.cpu_percent(interval=-1) def test_cpu_percent_numcpus_none(self): # See: https://github.com/giampaolo/psutil/issues/1087 with mock.patch('psutil.cpu_count', return_value=None) as m: psutil.Process().cpu_percent() assert m.called def test_cpu_times(self): times = psutil.Process().cpu_times() assert times.user >= 0.0, times assert times.system >= 0.0, times assert times.children_user >= 0.0, times assert times.children_system >= 0.0, times if LINUX: assert times.iowait >= 0.0, times # make sure returned values can be pretty printed with strftime for name in times._fields: time.strftime("%H:%M:%S", time.localtime(getattr(times, name))) @pytest.mark.skipif(not HAS_PROC_CPU_NUM, reason="not supported") def test_cpu_num(self): p = psutil.Process() num = p.cpu_num() assert num >= 0 if psutil.cpu_count() == 1: assert num == 0 assert p.cpu_num() in range(psutil.cpu_count()) def test_create_time(self): p = self.spawn_psproc() now = time.time() # Fail if the difference with current time is > 2s. assert abs(p.create_time() - now) < 2 # make sure returned value can be pretty printed with strftime time.strftime("%Y %m %d %H:%M:%S", time.localtime(p.create_time())) @pytest.mark.skipif(not POSIX, reason="POSIX only") def test_terminal(self): terminal = psutil.Process().terminal() if terminal is not None: try: tty = os.path.realpath(sh('tty')) except RuntimeError: # Note: happens if pytest is run without the `-s` opt. return pytest.skip("can't rely on `tty` CLI") else: assert terminal == tty @pytest.mark.skipif(not HAS_PROC_IO_COUNTERS, reason="not supported") @skip_on_not_implemented(only_if=LINUX) def test_io_counters(self): p = psutil.Process() # test reads io1 = p.io_counters() with open(PYTHON_EXE, 'rb') as f: f.read() io2 = p.io_counters() if not BSD and not AIX: assert io2.read_count > io1.read_count assert io2.write_count == io1.write_count if LINUX: assert io2.read_chars > io1.read_chars assert io2.write_chars == io1.write_chars else: assert io2.read_bytes >= io1.read_bytes assert io2.write_bytes >= io1.write_bytes # test writes io1 = p.io_counters() with open(self.get_testfn(), 'wb') as f: f.write(bytes("x" * 1000000, 'ascii')) io2 = p.io_counters() assert io2.write_count >= io1.write_count assert io2.write_bytes >= io1.write_bytes assert io2.read_count >= io1.read_count assert io2.read_bytes >= io1.read_bytes if LINUX: assert io2.write_chars > io1.write_chars assert io2.read_chars >= io1.read_chars # sanity check for i in range(len(io2)): if BSD and i >= 2: # On BSD read_bytes and write_bytes are always set to -1. continue assert io2[i] >= 0 assert io2[i] >= 0 @pytest.mark.skipif(not HAS_IONICE, reason="not supported") @pytest.mark.skipif(not LINUX, reason="linux only") def test_ionice_linux(self): def cleanup(init): ioclass, value = init if ioclass == psutil.IOPRIO_CLASS_NONE: value = 0 p.ionice(ioclass, value) p = psutil.Process() if not CI_TESTING: assert p.ionice()[0] == psutil.IOPRIO_CLASS_NONE assert psutil.IOPRIO_CLASS_NONE == 0 assert psutil.IOPRIO_CLASS_RT == 1 # high assert psutil.IOPRIO_CLASS_BE == 2 # normal assert psutil.IOPRIO_CLASS_IDLE == 3 # low init = p.ionice() self.addCleanup(cleanup, init) # low p.ionice(psutil.IOPRIO_CLASS_IDLE) assert tuple(p.ionice()) == (psutil.IOPRIO_CLASS_IDLE, 0) with pytest.raises(ValueError): # accepts no value p.ionice(psutil.IOPRIO_CLASS_IDLE, value=7) # normal p.ionice(psutil.IOPRIO_CLASS_BE) assert tuple(p.ionice()) == (psutil.IOPRIO_CLASS_BE, 0) p.ionice(psutil.IOPRIO_CLASS_BE, value=7) assert tuple(p.ionice()) == (psutil.IOPRIO_CLASS_BE, 7) with pytest.raises(ValueError): p.ionice(psutil.IOPRIO_CLASS_BE, value=8) try: p.ionice(psutil.IOPRIO_CLASS_RT, value=7) except psutil.AccessDenied: pass # errs with pytest.raises(ValueError, match="ioclass accepts no value"): p.ionice(psutil.IOPRIO_CLASS_NONE, 1) with pytest.raises(ValueError, match="ioclass accepts no value"): p.ionice(psutil.IOPRIO_CLASS_IDLE, 1) with pytest.raises( ValueError, match="'ioclass' argument must be specified" ): p.ionice(value=1) @pytest.mark.skipif(not HAS_IONICE, reason="not supported") @pytest.mark.skipif( not WINDOWS, reason="not supported on this win version" ) def test_ionice_win(self): p = psutil.Process() if not CI_TESTING: assert p.ionice() == psutil.IOPRIO_NORMAL init = p.ionice() self.addCleanup(p.ionice, init) # base p.ionice(psutil.IOPRIO_VERYLOW) assert p.ionice() == psutil.IOPRIO_VERYLOW p.ionice(psutil.IOPRIO_LOW) assert p.ionice() == psutil.IOPRIO_LOW try: p.ionice(psutil.IOPRIO_HIGH) except psutil.AccessDenied: pass else: assert p.ionice() == psutil.IOPRIO_HIGH # errs with pytest.raises( TypeError, match="value argument not accepted on Windows" ): p.ionice(psutil.IOPRIO_NORMAL, value=1) with pytest.raises(ValueError, match="is not a valid priority"): p.ionice(psutil.IOPRIO_HIGH + 1) @pytest.mark.skipif(not HAS_RLIMIT, reason="not supported") def test_rlimit_get(self): import resource p = psutil.Process(os.getpid()) names = [x for x in dir(psutil) if x.startswith('RLIMIT')] assert names, names for name in names: value = getattr(psutil, name) assert value >= 0 if name in dir(resource): assert value == getattr(resource, name) # XXX - On PyPy RLIMIT_INFINITY returned by # resource.getrlimit() is reported as a very big long # number instead of -1. It looks like a bug with PyPy. if PYPY: continue assert p.rlimit(value) == resource.getrlimit(value) else: ret = p.rlimit(value) assert len(ret) == 2 assert ret[0] >= -1 assert ret[1] >= -1 @pytest.mark.skipif(not HAS_RLIMIT, reason="not supported") def test_rlimit_set(self): p = self.spawn_psproc() p.rlimit(psutil.RLIMIT_NOFILE, (5, 5)) assert p.rlimit(psutil.RLIMIT_NOFILE) == (5, 5) # If pid is 0 prlimit() applies to the calling process and # we don't want that. if LINUX: with pytest.raises(ValueError, match="can't use prlimit"): psutil._psplatform.Process(0).rlimit(0) with pytest.raises(ValueError): p.rlimit(psutil.RLIMIT_NOFILE, (5, 5, 5)) @pytest.mark.skipif(not HAS_RLIMIT, reason="not supported") def test_rlimit(self): p = psutil.Process() testfn = self.get_testfn() soft, hard = p.rlimit(psutil.RLIMIT_FSIZE) try: p.rlimit(psutil.RLIMIT_FSIZE, (1024, hard)) with open(testfn, "wb") as f: f.write(b"X" * 1024) # write() or flush() doesn't always cause the exception # but close() will. with pytest.raises(OSError) as exc: with open(testfn, "wb") as f: f.write(b"X" * 1025) assert exc.value.errno == errno.EFBIG finally: p.rlimit(psutil.RLIMIT_FSIZE, (soft, hard)) assert p.rlimit(psutil.RLIMIT_FSIZE) == (soft, hard) @pytest.mark.skipif(not HAS_RLIMIT, reason="not supported") def test_rlimit_infinity(self): # First set a limit, then re-set it by specifying INFINITY # and assume we overridden the previous limit. p = psutil.Process() soft, hard = p.rlimit(psutil.RLIMIT_FSIZE) try: p.rlimit(psutil.RLIMIT_FSIZE, (1024, hard)) p.rlimit(psutil.RLIMIT_FSIZE, (psutil.RLIM_INFINITY, hard)) with open(self.get_testfn(), "wb") as f: f.write(b"X" * 2048) finally: p.rlimit(psutil.RLIMIT_FSIZE, (soft, hard)) assert p.rlimit(psutil.RLIMIT_FSIZE) == (soft, hard) @pytest.mark.skipif(not HAS_RLIMIT, reason="not supported") def test_rlimit_infinity_value(self): # RLIMIT_FSIZE should be RLIM_INFINITY, which will be a really # big number on a platform with large file support. On these # platforms we need to test that the get/setrlimit functions # properly convert the number to a C long long and that the # conversion doesn't raise an error. p = psutil.Process() soft, hard = p.rlimit(psutil.RLIMIT_FSIZE) assert hard == psutil.RLIM_INFINITY p.rlimit(psutil.RLIMIT_FSIZE, (soft, hard)) @pytest.mark.xdist_group(name="serial") def test_num_threads(self): # on certain platforms such as Linux we might test for exact # thread number, since we always have with 1 thread per process, # but this does not apply across all platforms (MACOS, Windows) p = psutil.Process() if OPENBSD: try: step1 = p.num_threads() except psutil.AccessDenied: return pytest.skip("on OpenBSD this requires root access") else: step1 = p.num_threads() with ThreadTask(): step2 = p.num_threads() assert step2 == step1 + 1 @pytest.mark.skipif(not WINDOWS, reason="WINDOWS only") def test_num_handles(self): # a better test is done later into test/_windows.py p = psutil.Process() assert p.num_handles() > 0 @pytest.mark.skipif(not HAS_THREADS, reason="not supported") def test_threads(self): p = psutil.Process() if OPENBSD: try: step1 = p.threads() except psutil.AccessDenied: return pytest.skip("on OpenBSD this requires root access") else: step1 = p.threads() with ThreadTask(): step2 = p.threads() assert len(step2) == len(step1) + 1 athread = step2[0] # test named tuple assert athread.id == athread[0] assert athread.user_time == athread[1] assert athread.system_time == athread[2] @retry_on_failure() @skip_on_access_denied(only_if=MACOS) @pytest.mark.skipif(not HAS_THREADS, reason="not supported") def test_threads_2(self): p = self.spawn_psproc() if OPENBSD: try: p.threads() except psutil.AccessDenied: return pytest.skip("on OpenBSD this requires root access") assert ( abs(p.cpu_times().user - sum(x.user_time for x in p.threads())) < 0.1 ) assert ( abs(p.cpu_times().system - sum(x.system_time for x in p.threads())) < 0.1 ) @retry_on_failure() def test_memory_info(self): p = psutil.Process() # step 1 - get a base value to compare our results rss1, vms1 = p.memory_info()[:2] percent1 = p.memory_percent() assert rss1 > 0 assert vms1 > 0 # step 2 - allocate some memory memarr = [None] * 1500000 rss2, vms2 = p.memory_info()[:2] percent2 = p.memory_percent() # step 3 - make sure that the memory usage bumped up assert rss2 > rss1 assert vms2 >= vms1 # vms might be equal assert percent2 > percent1 del memarr if WINDOWS: mem = p.memory_info() assert mem.rss == mem.wset assert mem.vms == mem.pagefile mem = p.memory_info() for name in mem._fields: assert getattr(mem, name) >= 0 def test_memory_full_info(self): p = psutil.Process() total = psutil.virtual_memory().total mem = p.memory_full_info() for name in mem._fields: value = getattr(mem, name) assert value >= 0 if (name == "vms" and OSX) or LINUX: continue assert value <= total if LINUX or WINDOWS or MACOS: assert mem.uss >= 0 if LINUX: assert mem.pss >= 0 assert mem.swap >= 0 @pytest.mark.skipif(not HAS_MEMORY_MAPS, reason="not supported") def test_memory_maps(self): p = psutil.Process() maps = p.memory_maps() assert len(maps) == len(set(maps)) ext_maps = p.memory_maps(grouped=False) for nt in maps: if nt.path.startswith('['): continue if BSD and nt.path == "pvclock": continue assert os.path.isabs(nt.path), nt.path if POSIX: try: assert os.path.exists(nt.path) or os.path.islink( nt.path ), nt.path except AssertionError: if not LINUX: raise # https://github.com/giampaolo/psutil/issues/759 with open_text('/proc/self/smaps') as f: data = f.read() if f"{nt.path} (deleted)" not in data: raise elif '64' not in os.path.basename(nt.path): # XXX - On Windows we have this strange behavior with # 64 bit dlls: they are visible via explorer but cannot # be accessed via os.stat() (wtf?). try: st = os.stat(nt.path) except FileNotFoundError: pass else: assert stat.S_ISREG(st.st_mode), nt.path for nt in ext_maps: for fname in nt._fields: value = getattr(nt, fname) if fname == 'path': continue if fname in {'addr', 'perms'}: assert value, value else: assert isinstance(value, int) assert value >= 0, value @pytest.mark.skipif(not HAS_MEMORY_MAPS, reason="not supported") def test_memory_maps_lists_lib(self): # Make sure a newly loaded shared lib is listed. p = psutil.Process() with copyload_shared_lib() as path: def normpath(p): return os.path.realpath(os.path.normcase(p)) libpaths = [normpath(x.path) for x in p.memory_maps()] assert normpath(path) in libpaths def test_memory_percent(self): p = psutil.Process() p.memory_percent() with pytest.raises(ValueError): p.memory_percent(memtype="?!?") if LINUX or MACOS or WINDOWS: p.memory_percent(memtype='uss') def test_is_running(self): p = self.spawn_psproc() assert p.is_running() assert p.is_running() p.kill() p.wait() assert not p.is_running() assert not p.is_running() def test_exe(self): p = self.spawn_psproc() exe = p.exe() try: assert exe == PYTHON_EXE except AssertionError: if WINDOWS and len(exe) == len(PYTHON_EXE): # on Windows we don't care about case sensitivity normcase = os.path.normcase assert normcase(exe) == normcase(PYTHON_EXE) else: # certain platforms such as BSD are more accurate returning: # "/usr/local/bin/python3.7" # ...instead of: # "/usr/local/bin/python" # We do not want to consider this difference in accuracy # an error. ver = f"{sys.version_info[0]}.{sys.version_info[1]}" try: assert exe.replace(ver, '') == PYTHON_EXE.replace(ver, '') except AssertionError: # Typically MACOS. Really not sure what to do here. pass out = sh([exe, "-c", "import os; print('hey')"]) assert out == 'hey' def test_cmdline(self): cmdline = [ PYTHON_EXE, "-c", "import time; [time.sleep(0.1) for x in range(100)]", ] p = self.spawn_psproc(cmdline) if NETBSD and p.cmdline() == []: # https://github.com/giampaolo/psutil/issues/2250 return pytest.skip("OPENBSD: returned EBUSY") # XXX - most of the times the underlying sysctl() call on Net # and Open BSD returns a truncated string. # Also /proc/pid/cmdline behaves the same so it looks # like this is a kernel bug. # XXX - AIX truncates long arguments in /proc/pid/cmdline if NETBSD or OPENBSD or AIX: assert p.cmdline()[0] == PYTHON_EXE else: if MACOS and CI_TESTING: pyexe = p.cmdline()[0] if pyexe != PYTHON_EXE: assert ' '.join(p.cmdline()[1:]) == ' '.join(cmdline[1:]) return None assert ' '.join(p.cmdline()) == ' '.join(cmdline) def test_long_cmdline(self): cmdline = [PYTHON_EXE] cmdline.extend(["-v"] * 50) cmdline.extend( ["-c", "import time; [time.sleep(0.1) for x in range(100)]"] ) p = self.spawn_psproc(cmdline) # XXX - flaky test: exclude the python exe which, for some # reason, and only sometimes, on OSX appears different. cmdline = cmdline[1:] if OPENBSD: # XXX: for some reason the test process may turn into a # zombie (don't know why). try: assert p.cmdline()[1:] == cmdline except psutil.ZombieProcess: return pytest.skip("OPENBSD: process turned into zombie") else: ret = p.cmdline()[1:] if NETBSD and ret == []: # https://github.com/giampaolo/psutil/issues/2250 return pytest.skip("OPENBSD: returned EBUSY") assert ret == cmdline def test_name(self): p = self.spawn_psproc() name = p.name().lower() if name.endswith("t"): # in the free-threaded build name = name[:-1] pyexe = os.path.basename(os.path.realpath(sys.executable)).lower() assert pyexe.startswith(name), (pyexe, name) @retry_on_failure() def test_long_name(self): pyexe = create_py_exe(self.get_testfn(suffix=string.digits * 2)) cmdline = [ pyexe, "-c", "import time; [time.sleep(0.1) for x in range(100)]", ] p = self.spawn_psproc(cmdline) if OPENBSD: # XXX: for some reason the test process may turn into a # zombie (don't know why). Because the name() is long, all # UNIX kernels truncate it to 15 chars, so internally psutil # tries to guess the full name() from the cmdline(). But the # cmdline() of a zombie on OpenBSD fails (internally), so we # just compare the first 15 chars. Full explanation: # https://github.com/giampaolo/psutil/issues/2239 try: assert p.name() == os.path.basename(pyexe) except AssertionError: if p.status() == psutil.STATUS_ZOMBIE: assert os.path.basename(pyexe).startswith(p.name()) else: raise else: assert p.name() == os.path.basename(pyexe) @pytest.mark.skipif(not POSIX, reason="POSIX only") def test_uids(self): p = psutil.Process() real, effective, _saved = p.uids() # os.getuid() refers to "real" uid assert real == os.getuid() # os.geteuid() refers to "effective" uid assert effective == os.geteuid() # No such thing as os.getsuid() ("saved" uid), but we have # os.getresuid() which returns all of them. if hasattr(os, "getresuid"): assert os.getresuid() == p.uids() @pytest.mark.skipif(not POSIX, reason="POSIX only") def test_gids(self): p = psutil.Process() real, effective, _saved = p.gids() # os.getuid() refers to "real" uid assert real == os.getgid() # os.geteuid() refers to "effective" uid assert effective == os.getegid() # No such thing as os.getsgid() ("saved" gid), but we have # os.getresgid() which returns all of them. if hasattr(os, "getresuid"): assert os.getresgid() == p.gids() def test_nice(self): def cleanup(init): try: p.nice(init) except psutil.AccessDenied: pass p = psutil.Process() with pytest.raises(TypeError): p.nice("str") init = p.nice() self.addCleanup(cleanup, init) if WINDOWS: highest_prio = None for prio in [ psutil.IDLE_PRIORITY_CLASS, psutil.BELOW_NORMAL_PRIORITY_CLASS, psutil.NORMAL_PRIORITY_CLASS, psutil.ABOVE_NORMAL_PRIORITY_CLASS, psutil.HIGH_PRIORITY_CLASS, psutil.REALTIME_PRIORITY_CLASS, ]: with self.subTest(prio=prio): try: p.nice(prio) except psutil.AccessDenied: pass else: new_prio = p.nice() # The OS may limit our maximum priority, # even if the function succeeds. For higher # priorities, we match either the expected # value or the highest so far. if prio in { psutil.ABOVE_NORMAL_PRIORITY_CLASS, psutil.HIGH_PRIORITY_CLASS, psutil.REALTIME_PRIORITY_CLASS, }: if new_prio == prio or highest_prio is None: highest_prio = prio assert new_prio == highest_prio else: assert new_prio == prio else: try: if hasattr(os, "getpriority"): assert ( os.getpriority(os.PRIO_PROCESS, os.getpid()) == p.nice() ) p.nice(1) assert p.nice() == 1 if hasattr(os, "getpriority"): assert ( os.getpriority(os.PRIO_PROCESS, os.getpid()) == p.nice() ) # XXX - going back to previous nice value raises # AccessDenied on MACOS if not MACOS: p.nice(0) assert p.nice() == 0 except psutil.AccessDenied: pass def test_status(self): p = psutil.Process() assert p.status() == psutil.STATUS_RUNNING def test_username(self): p = self.spawn_psproc() username = p.username() if WINDOWS: domain, username = username.split('\\') getpass_user = getpass.getuser() if getpass_user.endswith('$'): # When running as a service account (most likely to be # NetworkService), these user name calculations don't produce # the same result, causing the test to fail. return pytest.skip('running as service account') assert username == getpass_user if 'USERDOMAIN' in os.environ: assert domain == os.environ['USERDOMAIN'] else: assert username == getpass.getuser() def test_cwd(self): p = self.spawn_psproc() assert p.cwd() == os.getcwd() def test_cwd_2(self): cmd = [ PYTHON_EXE, "-c", ( "import os, time; os.chdir('..'); [time.sleep(0.1) for x in" " range(100)]" ), ] p = self.spawn_psproc(cmd) call_until(lambda: p.cwd() == os.path.dirname(os.getcwd())) @pytest.mark.skipif(not HAS_CPU_AFFINITY, reason="not supported") def test_cpu_affinity(self): p = psutil.Process() initial = p.cpu_affinity() assert initial, initial self.addCleanup(p.cpu_affinity, initial) if hasattr(os, "sched_getaffinity"): assert initial == list(os.sched_getaffinity(p.pid)) assert len(initial) == len(set(initial)) all_cpus = list(range(len(psutil.cpu_percent(percpu=True)))) for n in all_cpus: p.cpu_affinity([n]) assert p.cpu_affinity() == [n] if hasattr(os, "sched_getaffinity"): assert p.cpu_affinity() == list(os.sched_getaffinity(p.pid)) # also test num_cpu() if hasattr(p, "num_cpu"): assert p.cpu_affinity()[0] == p.num_cpu() # [] is an alias for "all eligible CPUs"; on Linux this may # not be equal to all available CPUs, see: # https://github.com/giampaolo/psutil/issues/956 p.cpu_affinity([]) if LINUX: assert p.cpu_affinity() == p._proc._get_eligible_cpus() else: assert p.cpu_affinity() == all_cpus if hasattr(os, "sched_getaffinity"): assert p.cpu_affinity() == list(os.sched_getaffinity(p.pid)) with pytest.raises(TypeError): p.cpu_affinity(1) p.cpu_affinity(initial) # it should work with all iterables, not only lists p.cpu_affinity(set(all_cpus)) p.cpu_affinity(tuple(all_cpus)) @pytest.mark.skipif(not HAS_CPU_AFFINITY, reason="not supported") def test_cpu_affinity_errs(self): p = self.spawn_psproc() invalid_cpu = [len(psutil.cpu_times(percpu=True)) + 10] with pytest.raises(ValueError): p.cpu_affinity(invalid_cpu) with pytest.raises(ValueError): p.cpu_affinity(range(10000, 11000)) with pytest.raises((TypeError, ValueError)): p.cpu_affinity([0, "1"]) with pytest.raises(ValueError): p.cpu_affinity([0, -1]) @pytest.mark.skipif(not HAS_CPU_AFFINITY, reason="not supported") def test_cpu_affinity_all_combinations(self): p = psutil.Process() initial = p.cpu_affinity() assert initial, initial self.addCleanup(p.cpu_affinity, initial) # All possible CPU set combinations. if len(initial) > 12: initial = initial[:12] # ...otherwise it will take forever combos = [] for i in range(len(initial) + 1): combos.extend( list(subset) for subset in itertools.combinations(initial, i) if subset ) for combo in combos: p.cpu_affinity(combo) assert sorted(p.cpu_affinity()) == sorted(combo) # TODO: #595 @pytest.mark.skipif(BSD, reason="broken on BSD") def test_open_files(self): p = psutil.Process() testfn = self.get_testfn() files = p.open_files() assert testfn not in files with open(testfn, 'wb') as f: f.write(b'x' * 1024) f.flush() # give the kernel some time to see the new file call_until(lambda: len(p.open_files()) != len(files)) files = p.open_files() filenames = [os.path.normcase(x.path) for x in files] assert os.path.normcase(testfn) in filenames if LINUX: for file in files: if file.path == testfn: assert file.position == 1024 for file in files: assert os.path.isfile(file.path), file # another process cmdline = ( f"import time; f = open(r'{testfn}', 'r'); [time.sleep(0.1) for x" " in range(100)];" ) p = self.spawn_psproc([PYTHON_EXE, "-c", cmdline]) for x in range(100): filenames = [os.path.normcase(x.path) for x in p.open_files()] if testfn in filenames: break time.sleep(0.01) else: assert os.path.normcase(testfn) in filenames for file in filenames: assert os.path.isfile(file), file # TODO: #595 @pytest.mark.skipif(BSD, reason="broken on BSD") def test_open_files_2(self): # test fd and path fields p = psutil.Process() normcase = os.path.normcase testfn = self.get_testfn() with open(testfn, 'w') as fileobj: for file in p.open_files(): if ( normcase(file.path) == normcase(fileobj.name) or file.fd == fileobj.fileno() ): break else: return pytest.fail(f"no file found; files={p.open_files()!r}") assert normcase(file.path) == normcase(fileobj.name) if WINDOWS: assert file.fd == -1 else: assert file.fd == fileobj.fileno() # test positions ntuple = p.open_files()[0] assert ntuple[0] == ntuple.path assert ntuple[1] == ntuple.fd # test file is gone assert fileobj.name not in p.open_files() @pytest.mark.skipif(not POSIX, reason="POSIX only") @pytest.mark.xdist_group(name="serial") def test_num_fds(self): p = psutil.Process() testfn = self.get_testfn() start = p.num_fds() with open(testfn, 'w'): assert p.num_fds() == start + 1 with socket.socket(): assert p.num_fds() == start + 2 assert p.num_fds() == start @skip_on_not_implemented(only_if=LINUX) @pytest.mark.skipif( OPENBSD or NETBSD, reason="not reliable on OPENBSD & NETBSD" ) def test_num_ctx_switches(self): p = psutil.Process() before = sum(p.num_ctx_switches()) for _ in range(2): time.sleep(0.05) # this shall ensure a context switch happens after = sum(p.num_ctx_switches()) if after > before: return None return pytest.fail( "num ctx switches still the same after 2 iterations" ) def test_ppid(self): p = psutil.Process() if hasattr(os, 'getppid'): assert p.ppid() == os.getppid() p = self.spawn_psproc() assert p.ppid() == os.getpid() def test_parent(self): p = self.spawn_psproc() assert p.parent().pid == os.getpid() lowest_pid = psutil.pids()[0] assert psutil.Process(lowest_pid).parent() is None def test_parent_mocked_ctime(self): # Make sure we get a fresh copy of the ctime before processing # parent().We make the assumption that the parent pid MUST have # a creation time < than the child. If system clock is updated # this assumption was broken. # https://github.com/giampaolo/psutil/issues/2542 p = self.spawn_psproc() p.create_time() # trigger cache assert p._create_time p._create_time = 1 assert p.parent().pid == os.getpid() def test_parent_multi(self): parent = psutil.Process() child, grandchild = self.spawn_children_pair() assert grandchild.parent() == child assert child.parent() == parent @retry_on_failure() def test_parents(self): parent = psutil.Process() assert parent.parents() child, grandchild = self.spawn_children_pair() assert child.parents()[0] == parent assert grandchild.parents()[0] == child assert grandchild.parents()[1] == parent def test_children(self): parent = psutil.Process() assert not parent.children() assert not parent.children(recursive=True) # On Windows we set the flag to 0 in order to cancel out the # CREATE_NO_WINDOW flag (enabled by default) which creates # an extra "conhost.exe" child. child = self.spawn_psproc(creationflags=0) children1 = parent.children() children2 = parent.children(recursive=True) for children in (children1, children2): assert len(children) == 1 assert children[0].pid == child.pid assert children[0].ppid() == parent.pid def test_children_mocked_ctime(self): # Make sure we get a fresh copy of the ctime before processing # children(). We make the assumption that process children MUST # have a creation time > than the parent. If system clock is # updated this assumption was broken. # https://github.com/giampaolo/psutil/issues/2542 parent = psutil.Process() parent.create_time() # trigger cache assert parent._create_time parent._create_time += 100000 assert not parent.children() assert not parent.children(recursive=True) # On Windows we set the flag to 0 in order to cancel out the # CREATE_NO_WINDOW flag (enabled by default) which creates # an extra "conhost.exe" child. child = self.spawn_psproc(creationflags=0) children1 = parent.children() children2 = parent.children(recursive=True) for children in (children1, children2): assert len(children) == 1 assert children[0].pid == child.pid assert children[0].ppid() == parent.pid def test_children_recursive(self): # Test children() against two sub processes, p1 and p2, where # p1 (our child) spawned p2 (our grandchild). parent = psutil.Process() child, grandchild = self.spawn_children_pair() assert parent.children() == [child] assert parent.children(recursive=True) == [child, grandchild] # If the intermediate process is gone there's no way for # children() to recursively find it. child.terminate() child.wait() assert not parent.children(recursive=True) def test_children_duplicates(self): # find the process which has the highest number of children table = collections.defaultdict(int) for p in psutil.process_iter(): try: table[p.ppid()] += 1 except psutil.Error: pass # this is the one, now let's make sure there are no duplicates pid = max(table.items(), key=lambda x: x[1])[0] if LINUX and pid == 0: return pytest.skip("PID 0") p = psutil.Process(pid) try: c = p.children(recursive=True) except psutil.AccessDenied: # windows pass else: assert len(c) == len(set(c)) def test_parents_and_children(self): parent = psutil.Process() child, grandchild = self.spawn_children_pair() # forward children = parent.children(recursive=True) assert len(children) == 2 assert children[0] == child assert children[1] == grandchild # backward parents = grandchild.parents() assert parents[0] == child assert parents[1] == parent def test_suspend_resume(self): p = self.spawn_psproc() p.suspend() for _ in range(100): if p.status() == psutil.STATUS_STOPPED: break time.sleep(0.01) p.resume() assert p.status() != psutil.STATUS_STOPPED def test_invalid_pid(self): with pytest.raises(TypeError): psutil.Process("1") with pytest.raises(ValueError): psutil.Process(-1) def test_as_dict(self): p = psutil.Process() d = p.as_dict(attrs=['exe', 'name']) assert sorted(d.keys()) == ['exe', 'name'] p = psutil.Process(min(psutil.pids())) d = p.as_dict(attrs=['net_connections'], ad_value='foo') if not isinstance(d['net_connections'], list): assert d['net_connections'] == 'foo' # Test ad_value is set on AccessDenied. with mock.patch( 'psutil.Process.nice', create=True, side_effect=psutil.AccessDenied ): assert p.as_dict(attrs=["nice"], ad_value=1) == {"nice": 1} # Test that NoSuchProcess bubbles up. with mock.patch( 'psutil.Process.nice', create=True, side_effect=psutil.NoSuchProcess(p.pid, "name"), ): with pytest.raises(psutil.NoSuchProcess): p.as_dict(attrs=["nice"]) # Test that ZombieProcess is swallowed. with mock.patch( 'psutil.Process.nice', create=True, side_effect=psutil.ZombieProcess(p.pid, "name"), ): assert p.as_dict(attrs=["nice"], ad_value="foo") == {"nice": "foo"} # By default APIs raising NotImplementedError are # supposed to be skipped. with mock.patch( 'psutil.Process.nice', create=True, side_effect=NotImplementedError ): d = p.as_dict() assert 'nice' not in list(d.keys()) # ...unless the user explicitly asked for some attr. with pytest.raises(NotImplementedError): p.as_dict(attrs=["nice"]) # errors with pytest.raises(TypeError): p.as_dict('name') with pytest.raises(ValueError): p.as_dict(['foo']) with pytest.raises(ValueError): p.as_dict(['foo', 'bar']) def test_oneshot(self): p = psutil.Process() with mock.patch("psutil._psplatform.Process.cpu_times") as m: with p.oneshot(): p.cpu_times() p.cpu_times() assert m.call_count == 1 with mock.patch("psutil._psplatform.Process.cpu_times") as m: p.cpu_times() p.cpu_times() assert m.call_count == 2 def test_oneshot_twice(self): # Test the case where the ctx manager is __enter__ed twice. # The second __enter__ is supposed to resut in a NOOP. p = psutil.Process() with mock.patch("psutil._psplatform.Process.cpu_times") as m1: with mock.patch("psutil._psplatform.Process.oneshot_enter") as m2: with p.oneshot(): p.cpu_times() p.cpu_times() with p.oneshot(): p.cpu_times() p.cpu_times() assert m1.call_count == 1 assert m2.call_count == 1 with mock.patch("psutil._psplatform.Process.cpu_times") as m: p.cpu_times() p.cpu_times() assert m.call_count == 2 def test_oneshot_cache(self): # Make sure oneshot() cache is nonglobal. Instead it's # supposed to be bound to the Process instance, see: # https://github.com/giampaolo/psutil/issues/1373 p1, p2 = self.spawn_children_pair() p1_ppid = p1.ppid() p2_ppid = p2.ppid() assert p1_ppid != p2_ppid with p1.oneshot(): assert p1.ppid() == p1_ppid assert p2.ppid() == p2_ppid with p2.oneshot(): assert p1.ppid() == p1_ppid assert p2.ppid() == p2_ppid def test_halfway_terminated_process(self): # Test that NoSuchProcess exception gets raised in case the # process dies after we create the Process object. # Example: # >>> proc = Process(1234) # >>> time.sleep(2) # time-consuming task, process dies in meantime # >>> proc.name() # Refers to Issue #15 def assert_raises_nsp(fun, fun_name): try: ret = fun() except psutil.ZombieProcess: # differentiate from NSP raise except psutil.NoSuchProcess: pass except psutil.AccessDenied: if OPENBSD and fun_name in {'threads', 'num_threads'}: return None raise else: # NtQuerySystemInformation succeeds even if process is gone. if WINDOWS and fun_name in {'exe', 'name'}: return None return pytest.fail( f"{fun!r} didn't raise NSP and returned {ret!r} instead" ) p = self.spawn_psproc() p.terminate() p.wait() if WINDOWS: # XXX call_until(lambda: p.pid not in psutil.pids()) self.assert_proc_gone(p) ns = process_namespace(p) for fun, name in ns.iter(ns.all): assert_raises_nsp(fun, name) @pytest.mark.skipif(not POSIX, reason="POSIX only") def test_zombie_process(self): _parent, zombie = self.spawn_zombie() self.assert_proc_zombie(zombie) if hasattr(psutil._psplatform.cext, "proc_is_zombie"): assert not psutil._psplatform.cext.proc_is_zombie(os.getpid()) assert psutil._psplatform.cext.proc_is_zombie(zombie.pid) @pytest.mark.skipif(not POSIX, reason="POSIX only") def test_zombie_process_is_running_w_exc(self): # Emulate a case where internally is_running() raises # ZombieProcess. p = psutil.Process() with mock.patch( "psutil.Process", side_effect=psutil.ZombieProcess(0) ) as m: assert p.is_running() assert m.called @pytest.mark.skipif(not POSIX, reason="POSIX only") def test_zombie_process_status_w_exc(self): # Emulate a case where internally status() raises # ZombieProcess. p = psutil.Process() with mock.patch( "psutil._psplatform.Process.status", side_effect=psutil.ZombieProcess(0), ) as m: assert p.status() == psutil.STATUS_ZOMBIE assert m.called def test_reused_pid(self): # Emulate a case where PID has been reused by another process. subp = self.spawn_subproc() p = psutil.Process(subp.pid) p._ident = (p.pid, p.create_time() + 100) list(psutil.process_iter()) assert p.pid in psutil._pmap assert not p.is_running() # make sure is_running() removed PID from process_iter() # internal cache with mock.patch.object(psutil._common, "PSUTIL_DEBUG", True): with contextlib.redirect_stderr(io.StringIO()) as f: list(psutil.process_iter()) assert ( f"refreshing Process instance for reused PID {p.pid}" in f.getvalue() ) assert p.pid not in psutil._pmap assert p != psutil.Process(subp.pid) msg = "process no longer exists and its PID has been reused" ns = process_namespace(p) for fun, name in ns.iter(ns.setters + ns.killers, clear_cache=False): with self.subTest(name=name): with pytest.raises(psutil.NoSuchProcess, match=msg): fun() assert "terminated + PID reused" in str(p) assert "terminated + PID reused" in repr(p) with pytest.raises(psutil.NoSuchProcess, match=msg): p.ppid() with pytest.raises(psutil.NoSuchProcess, match=msg): p.parent() with pytest.raises(psutil.NoSuchProcess, match=msg): p.parents() with pytest.raises(psutil.NoSuchProcess, match=msg): p.children() def test_pid_0(self): # Process(0) is supposed to work on all platforms except Linux if 0 not in psutil.pids(): with pytest.raises(psutil.NoSuchProcess): psutil.Process(0) # These 2 are a contradiction, but "ps" says PID 1's parent # is PID 0. assert not psutil.pid_exists(0) assert psutil.Process(1).ppid() == 0 return p = psutil.Process(0) exc = psutil.AccessDenied if WINDOWS else ValueError with pytest.raises(exc): p.wait() with pytest.raises(exc): p.terminate() with pytest.raises(exc): p.suspend() with pytest.raises(exc): p.resume() with pytest.raises(exc): p.kill() with pytest.raises(exc): p.send_signal(signal.SIGTERM) # test all methods ns = process_namespace(p) for fun, name in ns.iter(ns.getters + ns.setters): try: ret = fun() except psutil.AccessDenied: pass else: if name in {"uids", "gids"}: assert ret.real == 0 elif name == "username": user = 'NT AUTHORITY\\SYSTEM' if WINDOWS else 'root' assert p.username() == user elif name == "name": assert name, name if not OPENBSD: assert 0 in psutil.pids() assert psutil.pid_exists(0) @pytest.mark.skipif(not HAS_ENVIRON, reason="not supported") def test_environ(self): def clean_dict(d): exclude = {"PLAT", "HOME"} if MACOS: exclude.update([ "__CF_USER_TEXT_ENCODING", "VERSIONER_PYTHON_PREFER_32_BIT", "VERSIONER_PYTHON_VERSION", ]) for name in list(d.keys()): if name in exclude or name.startswith("PYTEST_"): d.pop(name) return { k.replace("\r", "").replace("\n", ""): ( v.replace("\r", "").replace("\n", "") ) for k, v in d.items() } self.maxDiff = None p = psutil.Process() d1 = clean_dict(p.environ()) d2 = clean_dict(os.environ.copy()) if not OSX and GITHUB_ACTIONS: assert d1 == d2 @pytest.mark.skipif(not HAS_ENVIRON, reason="not supported") @pytest.mark.skipif(not POSIX, reason="POSIX only") @pytest.mark.skipif( MACOS_11PLUS, reason="macOS 11+ can't get another process environment, issue #2084", ) @pytest.mark.skipif( NETBSD, reason="sometimes fails on `assert is_running()`" ) def test_weird_environ(self): # environment variables can contain values without an equals sign code = textwrap.dedent(""" #include <unistd.h> #include <fcntl.h> char * const argv[] = {"cat", 0}; char * const envp[] = {"A=1", "X", "C=3", 0}; int main(void) { // Close stderr on exec so parent can wait for the // execve to finish. if (fcntl(2, F_SETFD, FD_CLOEXEC) != 0) return 0; return execve("/bin/cat", argv, envp); } """) cexe = create_c_exe(self.get_testfn(), c_code=code) sproc = self.spawn_subproc( [cexe], stdin=subprocess.PIPE, stderr=subprocess.PIPE ) p = psutil.Process(sproc.pid) wait_for_pid(p.pid) assert p.is_running() # Wait for process to exec or exit. assert sproc.stderr.read() == b"" if MACOS and CI_TESTING: try: env = p.environ() except psutil.AccessDenied: # XXX: fails sometimes with: # PermissionError from 'sysctl(KERN_PROCARGS2) -> EIO' return else: env = p.environ() assert env == {"A": "1", "C": "3"} sproc.communicate() assert sproc.returncode == 0 # =================================================================== # --- psutil.Popen tests # ===================================================================
TestProcess
python
wandb__wandb
wandb/sdk/launch/agent/agent.py
{ "start": 3129, "end": 4927 }
class ____: def __init__(self, verbosity=0): self._print_to_terminal = verbosity >= 2 def error(self, message: str): if self._print_to_terminal: wandb.termerror(f"{LOG_PREFIX}{message}") _logger.error(f"{LOG_PREFIX}{message}") def warn(self, message: str): if self._print_to_terminal: wandb.termwarn(f"{LOG_PREFIX}{message}") _logger.warning(f"{LOG_PREFIX}{message}") def info(self, message: str): if self._print_to_terminal: wandb.termlog(f"{LOG_PREFIX}{message}") _logger.info(f"{LOG_PREFIX}{message}") def debug(self, message: str): if self._print_to_terminal: wandb.termlog(f"{LOG_PREFIX}{message}") _logger.debug(f"{LOG_PREFIX}{message}") def construct_agent_configs( launch_config: Optional[Dict] = None, build_config: Optional[Dict] = None, ) -> Tuple[Optional[Dict[str, Any]], Dict[str, Any], Dict[str, Any]]: import yaml registry_config = None environment_config = None if launch_config is not None: build_config = launch_config.get("builder") registry_config = launch_config.get("registry") default_launch_config = None if os.path.exists(os.path.expanduser(LAUNCH_CONFIG_FILE)): with open(os.path.expanduser(LAUNCH_CONFIG_FILE)) as f: default_launch_config = ( yaml.safe_load(f) or {} ) # In case the config is empty, we want it to be {} instead of None. environment_config = default_launch_config.get("environment") build_config, registry_config = resolve_build_and_registry_config( default_launch_config, build_config, registry_config ) return environment_config, build_config, registry_config
InternalAgentLogger
python
huggingface__transformers
src/transformers/models/convbert/modeling_convbert.py
{ "start": 15142, "end": 15983 }
class ____(nn.Module): def __init__(self, config): super().__init__() if config.num_groups == 1: self.dense = nn.Linear(config.intermediate_size, config.hidden_size) else: self.dense = GroupedLinearLayer( input_size=config.intermediate_size, output_size=config.hidden_size, num_groups=config.num_groups ) self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) self.dropout = nn.Dropout(config.hidden_dropout_prob) def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor: hidden_states = self.dense(hidden_states) hidden_states = self.dropout(hidden_states) hidden_states = self.LayerNorm(hidden_states + input_tensor) return hidden_states
ConvBertOutput
python
huggingface__transformers
tests/models/maskformer/test_modeling_maskformer.py
{ "start": 1611, "end": 7741 }
class ____: def __init__( self, parent, batch_size=2, is_training=True, use_auxiliary_loss=False, num_queries=10, num_channels=3, min_size=32 * 4, max_size=32 * 6, num_labels=4, mask_feature_size=32, num_hidden_layers=2, num_attention_heads=2, ): self.parent = parent self.batch_size = batch_size self.is_training = is_training self.use_auxiliary_loss = use_auxiliary_loss self.num_queries = num_queries self.num_channels = num_channels self.min_size = min_size self.max_size = max_size self.num_labels = num_labels self.mask_feature_size = mask_feature_size # This is passed to the decoder config. We add it to the model tester here for testing self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads def prepare_config_and_inputs(self): pixel_values = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size]).to( torch_device ) pixel_mask = torch.ones([self.batch_size, self.min_size, self.max_size], device=torch_device) mask_labels = ( torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size], device=torch_device) > 0.5 ).float() class_labels = (torch.rand((self.batch_size, self.num_labels), device=torch_device) > 0.5).long() config = self.get_config() return config, pixel_values, pixel_mask, mask_labels, class_labels def get_config(self): return MaskFormerConfig( backbone_config=SwinConfig( depths=[1, 1, 1, 1], embed_dim=16, hidden_size=32, num_heads=[1, 1, 2, 2], ), backbone=None, decoder_config=DetrConfig( decoder_ffn_dim=64, decoder_layers=self.num_hidden_layers, decoder_attention_heads=self.num_attention_heads, encoder_ffn_dim=64, encoder_layers=self.num_hidden_layers, encoder_attention_heads=self.num_attention_heads, num_queries=self.num_queries, d_model=self.mask_feature_size, ), mask_feature_size=self.mask_feature_size, fpn_feature_size=self.mask_feature_size, num_channels=self.num_channels, num_labels=self.num_labels, ) def prepare_config_and_inputs_for_common(self): config, pixel_values, pixel_mask, _, _ = self.prepare_config_and_inputs() inputs_dict = {"pixel_values": pixel_values, "pixel_mask": pixel_mask} return config, inputs_dict def check_output_hidden_state(self, output, config): encoder_hidden_states = output.encoder_hidden_states pixel_decoder_hidden_states = output.pixel_decoder_hidden_states transformer_decoder_hidden_states = output.transformer_decoder_hidden_states self.parent.assertTrue(len(encoder_hidden_states), len(config.backbone_config.depths)) self.parent.assertTrue(len(pixel_decoder_hidden_states), len(config.backbone_config.depths)) self.parent.assertTrue(len(transformer_decoder_hidden_states), config.decoder_config.decoder_layers) def create_and_check_maskformer_model(self, config, pixel_values, pixel_mask, output_hidden_states=False): with torch.no_grad(): model = MaskFormerModel(config=config) model.to(torch_device) model.eval() output = model(pixel_values=pixel_values, pixel_mask=pixel_mask) output = model(pixel_values, output_hidden_states=True) # the correct shape of output.transformer_decoder_hidden_states ensure the correctness of the # encoder and pixel decoder self.parent.assertEqual( output.transformer_decoder_last_hidden_state.shape, (self.batch_size, self.num_queries, self.mask_feature_size), ) # let's ensure the other two hidden state exists self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None) self.parent.assertTrue(output.encoder_last_hidden_state is not None) if output_hidden_states: self.check_output_hidden_state(output, config) def create_and_check_maskformer_instance_segmentation_head_model( self, config, pixel_values, pixel_mask, mask_labels, class_labels ): model = MaskFormerForInstanceSegmentation(config=config) model.to(torch_device) model.eval() def comm_check_on_output(result): # let's still check that all the required stuff is there self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None) self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None) self.parent.assertTrue(result.encoder_last_hidden_state is not None) # okay, now we need to check the logits shape # due to the encoder compression, masks have a //4 spatial size self.parent.assertEqual( result.masks_queries_logits.shape, (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4), ) # + 1 for null class self.parent.assertEqual( result.class_queries_logits.shape, (self.batch_size, self.num_queries, self.num_labels + 1) ) with torch.no_grad(): result = model(pixel_values=pixel_values, pixel_mask=pixel_mask) result = model(pixel_values) comm_check_on_output(result) result = model( pixel_values=pixel_values, pixel_mask=pixel_mask, mask_labels=mask_labels, class_labels=class_labels ) comm_check_on_output(result) self.parent.assertTrue(result.loss is not None) self.parent.assertEqual(result.loss.shape, torch.Size([])) @require_torch
MaskFormerModelTester
python
pandas-dev__pandas
pandas/tests/frame/test_arrow_interface.py
{ "start": 1740, "end": 2948 }
class ____: def __init__(self, table): self.stream = table def __arrow_c_stream__(self, requested_schema=None): return self.stream.__arrow_c_stream__(requested_schema) @td.skip_if_no("pyarrow", min_version="14.0") def test_dataframe_from_arrow(): # objects with __arrow_c_stream__ table = pa.table({"a": [1, 2, 3], "b": ["a", "b", "c"]}) result = pd.DataFrame.from_arrow(table) expected = pd.DataFrame({"a": [1, 2, 3], "b": ["a", "b", "c"]}) tm.assert_frame_equal(result, expected) # not only pyarrow object are supported result = pd.DataFrame.from_arrow(ArrowStreamWrapper(table)) tm.assert_frame_equal(result, expected) # objects with __arrow_c_array__ batch = pa.record_batch([[1, 2, 3], ["a", "b", "c"]], names=["a", "b"]) result = pd.DataFrame.from_arrow(table) tm.assert_frame_equal(result, expected) result = pd.DataFrame.from_arrow(ArrowArrayWrapper(batch)) tm.assert_frame_equal(result, expected) # only accept actual Arrow objects with pytest.raises(TypeError, match="Expected an Arrow-compatible tabular object"): pd.DataFrame.from_arrow({"a": [1, 2, 3], "b": ["a", "b", "c"]})
ArrowStreamWrapper
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/hooks/datafusion.py
{ "start": 2092, "end": 21388 }
class ____(GoogleBaseHook): """Hook for Google DataFusion.""" _conn: Resource | None = None def __init__( self, api_version: str = "v1beta1", gcp_conn_id: str = "google_cloud_default", impersonation_chain: str | Sequence[str] | None = None, **kwargs, ) -> None: super().__init__( gcp_conn_id=gcp_conn_id, impersonation_chain=impersonation_chain, **kwargs, ) self.api_version = api_version def wait_for_operation(self, operation: dict[str, Any]) -> dict[str, Any]: """Wait for long-lasting operation to complete.""" for time_to_wait in exponential_sleep_generator(initial=10, maximum=120): time.sleep(time_to_wait) operation = ( self.get_conn().projects().locations().operations().get(name=operation.get("name")).execute() ) if operation.get("done"): break if "error" in operation: raise AirflowException(operation["error"]) return operation["response"] def wait_for_pipeline_state( self, pipeline_name: str, pipeline_id: str, instance_url: str, pipeline_type: DataFusionPipelineType = DataFusionPipelineType.BATCH, namespace: str = "default", success_states: list[str] | None = None, failure_states: list[str] | None = None, timeout: int = 5 * 60, ) -> None: """Poll for pipeline state and raises an exception if the state fails or times out.""" failure_states = failure_states or FAILURE_STATES success_states = success_states or SUCCESS_STATES start_time = time.monotonic() current_state = None while time.monotonic() - start_time < timeout: try: workflow = self.get_pipeline_workflow( pipeline_name=pipeline_name, pipeline_id=pipeline_id, pipeline_type=pipeline_type, instance_url=instance_url, namespace=namespace, ) current_state = workflow["status"] except AirflowException: pass # Because the pipeline may not be visible in system yet if current_state in success_states: return if current_state in failure_states: raise AirflowException( f"Pipeline {pipeline_name} state {current_state} is not one of {success_states}" ) time.sleep(30) # Time is up! raise AirflowException( f"Pipeline {pipeline_name} state {current_state} is not one of {success_states} after {timeout}s" ) @staticmethod def _name(project_id: str, location: str, instance_name: str) -> str: return f"projects/{project_id}/locations/{location}/instances/{instance_name}" @staticmethod def _parent(project_id: str, location: str) -> str: return f"projects/{project_id}/locations/{location}" @staticmethod def _base_url(instance_url: str, namespace: str) -> str: return os.path.join(instance_url, "v3", "namespaces", quote(namespace), "apps") def _cdap_request( self, url: str, method: str, body: list | dict | None = None, params: dict | None = None ) -> google.auth.transport.Response: headers: dict[str, str] = {"Content-Type": "application/json"} request = google.auth.transport.requests.Request() credentials = self.get_credentials() credentials.before_request(request=request, method=method, url=url, headers=headers) payload = json.dumps(body) if body else None response = request(method=method, url=url, headers=headers, body=payload, params=params) return response @staticmethod def _check_response_status_and_data(response, message: str) -> None: if response.status == 404: raise AirflowNotFoundException(message) if response.status == 409: raise ConflictException("Conflict: Resource is still in use.") if response.status != 200: raise AirflowException(message) if response.data is None: raise AirflowException( "Empty response received. Please, check for possible root " "causes of this behavior either in DAG code or on Cloud DataFusion side" ) def get_conn(self) -> Resource: """Retrieve connection to DataFusion.""" if not self._conn: http_authorized = self._authorize() self._conn = build( "datafusion", self.api_version, http=http_authorized, cache_discovery=False, ) return self._conn @GoogleBaseHook.fallback_to_default_project_id def restart_instance(self, instance_name: str, location: str, project_id: str) -> Operation: """ Restart a single Data Fusion instance. At the end of an operation instance is fully restarted. :param instance_name: The name of the instance to restart. :param location: The Cloud Data Fusion location in which to handle the request. :param project_id: The ID of the Google Cloud project that the instance belongs to. """ operation = ( self.get_conn() .projects() .locations() .instances() .restart(name=self._name(project_id, location, instance_name)) .execute(num_retries=self.num_retries) ) return operation @GoogleBaseHook.fallback_to_default_project_id def delete_instance(self, instance_name: str, location: str, project_id: str) -> Operation: """ Delete a single Date Fusion instance. :param instance_name: The name of the instance to delete. :param location: The Cloud Data Fusion location in which to handle the request. :param project_id: The ID of the Google Cloud project that the instance belongs to. """ operation = ( self.get_conn() .projects() .locations() .instances() .delete(name=self._name(project_id, location, instance_name)) .execute(num_retries=self.num_retries) ) return operation @GoogleBaseHook.fallback_to_default_project_id def create_instance( self, instance_name: str, instance: dict[str, Any], location: str, project_id: str = PROVIDE_PROJECT_ID, ) -> Operation: """ Create a new Data Fusion instance in the specified project and location. :param instance_name: The name of the instance to create. :param instance: An instance of Instance. https://cloud.google.com/data-fusion/docs/reference/rest/v1beta1/projects.locations.instances#Instance :param location: The Cloud Data Fusion location in which to handle the request. :param project_id: The ID of the Google Cloud project that the instance belongs to. """ operation = ( self.get_conn() .projects() .locations() .instances() .create( parent=self._parent(project_id, location), body=instance, instanceId=instance_name, ) .execute(num_retries=self.num_retries) ) return operation @GoogleBaseHook.fallback_to_default_project_id def get_instance(self, instance_name: str, location: str, project_id: str) -> dict[str, Any]: """ Get details of a single Data Fusion instance. :param instance_name: The name of the instance. :param location: The Cloud Data Fusion location in which to handle the request. :param project_id: The ID of the Google Cloud project that the instance belongs to. """ instance = ( self.get_conn() .projects() .locations() .instances() .get(name=self._name(project_id, location, instance_name)) .execute(num_retries=self.num_retries) ) return instance def get_instance_artifacts( self, instance_url: str, namespace: str = "default", scope: str = "SYSTEM" ) -> Any: url = os.path.join( instance_url, "v3", "namespaces", quote(namespace), "artifacts", ) response = self._cdap_request(url=url, method="GET", params={"scope": scope}) self._check_response_status_and_data( response, f"Retrieving an instance artifacts failed with code {response.status}" ) content = json.loads(response.data) return content @GoogleBaseHook.fallback_to_default_project_id def patch_instance( self, instance_name: str, instance: dict[str, Any], update_mask: str, location: str, project_id: str = PROVIDE_PROJECT_ID, ) -> Operation: """ Update a single Data Fusion instance. :param instance_name: The name of the instance to create. :param instance: An instance of Instance. https://cloud.google.com/data-fusion/docs/reference/rest/v1beta1/projects.locations.instances#Instance :param update_mask: Field mask is used to specify the fields that the update will overwrite in an instance resource. The fields specified in the updateMask are relative to the resource, not the full request. A field will be overwritten if it is in the mask. If the user does not provide a mask, all the supported fields (labels and options currently) will be overwritten. A comma-separated list of fully qualified names of fields. Example: "user.displayName,photo". https://developers.google.com/protocol-buffers/docs/reference/google.protobuf?_ga=2.205612571.-968688242.1573564810#google.protobuf.FieldMask :param location: The Cloud Data Fusion location in which to handle the request. :param project_id: The ID of the Google Cloud project that the instance belongs to. """ operation = ( self.get_conn() .projects() .locations() .instances() .patch( name=self._name(project_id, location, instance_name), updateMask=update_mask, body=instance, ) .execute(num_retries=self.num_retries) ) return operation def create_pipeline( self, pipeline_name: str, pipeline: dict[str, Any], instance_url: str, namespace: str = "default", ) -> None: """ Create a batch Cloud Data Fusion pipeline. :param pipeline_name: Your pipeline name. :param pipeline: The pipeline definition. For more information check: https://docs.cdap.io/cdap/current/en/developer-manual/pipelines/developing-pipelines.html#pipeline-configuration-file-format :param instance_url: Endpoint on which the REST APIs is accessible for the instance. :param namespace: if your pipeline belongs to a Basic edition instance, the namespace ID is always default. If your pipeline belongs to an Enterprise edition instance, you can create a namespace. """ url = os.path.join(self._base_url(instance_url, namespace), quote(pipeline_name)) response = self._cdap_request(url=url, method="PUT", body=pipeline) self._check_response_status_and_data( response, f"Creating a pipeline failed with code {response.status} while calling {url}" ) def delete_pipeline( self, pipeline_name: str, instance_url: str, version_id: str | None = None, namespace: str = "default", ) -> None: """ Delete a batch Cloud Data Fusion pipeline. :param pipeline_name: Your pipeline name. :param version_id: Version of pipeline to delete :param instance_url: Endpoint on which the REST APIs is accessible for the instance. :param namespace: if your pipeline belongs to a Basic edition instance, the namespace ID is always default. If your pipeline belongs to an Enterprise edition instance, you can create a namespace. """ url = os.path.join(self._base_url(instance_url, namespace), quote(pipeline_name)) if version_id: url = os.path.join(url, "versions", version_id) for time_to_wait in exponential_sleep_generator(initial=1, maximum=10): try: response = self._cdap_request(url=url, method="DELETE", body=None) self._check_response_status_and_data( response, f"Deleting a pipeline failed with code {response.status}: {response.data}" ) except ConflictException as exc: self.log.info(exc) time.sleep(time_to_wait) else: if response.status == 200: break def list_pipelines( self, instance_url: str, artifact_name: str | None = None, artifact_version: str | None = None, namespace: str = "default", ) -> dict: """ List Cloud Data Fusion pipelines. :param artifact_version: Artifact version to filter instances :param artifact_name: Artifact name to filter instances :param instance_url: Endpoint on which the REST APIs is accessible for the instance. :param namespace: f your pipeline belongs to a Basic edition instance, the namespace ID is always default. If your pipeline belongs to an Enterprise edition instance, you can create a namespace. """ url = self._base_url(instance_url, namespace) query: dict[str, str] = {} if artifact_name: query = {"artifactName": artifact_name} if artifact_version: query = {"artifactVersion": artifact_version} if query: url = os.path.join(url, urlencode(query)) response = self._cdap_request(url=url, method="GET", body=None) self._check_response_status_and_data( response, f"Listing pipelines failed with code {response.status}" ) return json.loads(response.data) def get_pipeline_workflow( self, pipeline_name: str, instance_url: str, pipeline_id: str, pipeline_type: DataFusionPipelineType = DataFusionPipelineType.BATCH, namespace: str = "default", ) -> dict: url = os.path.join( self._base_url(instance_url, namespace), quote(pipeline_name), f"{self.cdap_program_type(pipeline_type=pipeline_type)}s", self.cdap_program_id(pipeline_type=pipeline_type), "runs", quote(pipeline_id), ) response = self._cdap_request(url=url, method="GET") self._check_response_status_and_data( response, f"Retrieving a pipeline state failed with code {response.status}" ) workflow = json.loads(response.data) return workflow def start_pipeline( self, pipeline_name: str, instance_url: str, pipeline_type: DataFusionPipelineType = DataFusionPipelineType.BATCH, namespace: str = "default", runtime_args: dict[str, Any] | None = None, ) -> str: """ Start a Cloud Data Fusion pipeline. Works for both batch and stream pipelines. :param pipeline_name: Your pipeline name. :param pipeline_type: Optional pipeline type (BATCH by default). :param instance_url: Endpoint on which the REST APIs is accessible for the instance. :param runtime_args: Optional runtime JSON args to be passed to the pipeline :param namespace: if your pipeline belongs to a Basic edition instance, the namespace ID is always default. If your pipeline belongs to an Enterprise edition instance, you can create a namespace. """ # TODO: This API endpoint starts multiple pipelines. There will eventually be a fix # return the run Id as part of the API request to run a single pipeline. # https://github.com/apache/airflow/pull/8954#discussion_r438223116 url = os.path.join( instance_url, "v3", "namespaces", quote(namespace), "start", ) runtime_args = runtime_args or {} body = [ { "appId": pipeline_name, "runtimeargs": runtime_args, "programType": self.cdap_program_type(pipeline_type=pipeline_type), "programId": self.cdap_program_id(pipeline_type=pipeline_type), } ] response = self._cdap_request(url=url, method="POST", body=body) self._check_response_status_and_data( response, f"Starting a pipeline failed with code {response.status}" ) response_json = json.loads(response.data) return response_json[0]["runId"] def stop_pipeline(self, pipeline_name: str, instance_url: str, namespace: str = "default") -> None: """ Stop a Cloud Data Fusion pipeline. Works for both batch and stream pipelines. :param pipeline_name: Your pipeline name. :param instance_url: Endpoint on which the REST APIs is accessible for the instance. :param namespace: f your pipeline belongs to a Basic edition instance, the namespace ID is always default. If your pipeline belongs to an Enterprise edition instance, you can create a namespace. """ url = os.path.join( self._base_url(instance_url, namespace), quote(pipeline_name), "workflows", "DataPipelineWorkflow", "stop", ) response = self._cdap_request(url=url, method="POST") self._check_response_status_and_data( response, f"Stopping a pipeline failed with code {response.status}" ) @staticmethod def cdap_program_type(pipeline_type: DataFusionPipelineType) -> str: """ Retrieve CDAP Program type depending on the pipeline type. :param pipeline_type: Pipeline type. """ program_types = { DataFusionPipelineType.BATCH: "workflow", DataFusionPipelineType.STREAM: "spark", } return program_types.get(pipeline_type, "") @staticmethod def cdap_program_id(pipeline_type: DataFusionPipelineType) -> str: """ Retrieve CDAP Program id depending on the pipeline type. :param pipeline_type: Pipeline type. """ program_ids = { DataFusionPipelineType.BATCH: "DataPipelineWorkflow", DataFusionPipelineType.STREAM: "DataStreamsSparkStreaming", } return program_ids.get(pipeline_type, "")
DataFusionHook
python
tensorflow__tensorflow
tensorflow/python/distribute/distribute_lib.py
{ "start": 169185, "end": 170451 }
class ____(object): """Context manager setting the default `tf.distribute.Strategy`.""" __slots__ = ["_var_creator_scope", "_strategy", "_nested_count"] def __init__(self, strategy): def creator(next_creator, **kwargs): _require_strategy_scope_strategy(strategy) return next_creator(**kwargs) self._var_creator_scope = variable_scope.variable_creator_scope(creator) self._strategy = strategy self._nested_count = 0 def __enter__(self): # Allow this scope to be entered if this strategy is already in scope. if has_strategy(): raise RuntimeError("Must not nest tf.distribute.Strategy scopes.") if self._nested_count == 0: self._var_creator_scope.__enter__() self._nested_count += 1 return self._strategy def __exit__(self, exception_type, exception_value, traceback): self._nested_count -= 1 if self._nested_count == 0: try: self._var_creator_scope.__exit__( exception_type, exception_value, traceback) except RuntimeError as e: six.raise_from( RuntimeError("Variable creator scope nesting error: move call to " "tf.distribute.set_strategy() out of `with` scope."), e)
_DefaultDistributionContext
python
joerick__pyinstrument
test/low_level/test_custom_timer.py
{ "start": 71, "end": 641 }
class ____: def __init__(self) -> None: self.count = 0 def __call__(self, *args: Any, **kwds: Any) -> Any: self.count += 1 @parametrize_setstatprofile def test_increment(setstatprofile): time = 0.0 def fake_time(): return time def fake_sleep(duration): nonlocal time time += duration counter = CallCounter() setstatprofile(counter, timer_func=fake_time, timer_type="timer_func") for _ in range(100): fake_sleep(1.0) setstatprofile(None) assert counter.count == 100
CallCounter
python
numpy__numpy
numpy/_core/tests/test_scalarmath.py
{ "start": 30080, "end": 30554 }
class ____: def test_exceptions(self): a = np.ones((), dtype=np.bool)[()] assert_raises(TypeError, operator.sub, a, a) def test_result(self): types = np.typecodes['AllInteger'] + np.typecodes['AllFloat'] with warnings.catch_warnings(): warnings.simplefilter('ignore', RuntimeWarning) for dt in types: a = np.ones((), dtype=dt)[()] assert_equal(operator.sub(a, a), 0)
TestSubtract
python
huggingface__transformers
tests/models/distilbert/test_modeling_distilbert.py
{ "start": 1536, "end": 8160 }
class ____: def __init__( self, parent, batch_size=13, seq_length=7, is_training=True, use_input_mask=True, use_token_type_ids=False, use_labels=True, vocab_size=99, hidden_size=32, num_hidden_layers=2, num_attention_heads=4, intermediate_size=37, hidden_act="gelu", hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, max_position_embeddings=512, type_vocab_size=16, type_sequence_label_size=2, initializer_range=0.02, num_labels=3, num_choices=4, scope=None, ): self.parent = parent self.batch_size = batch_size self.seq_length = seq_length self.is_training = is_training self.use_input_mask = use_input_mask self.use_token_type_ids = use_token_type_ids self.use_labels = use_labels self.vocab_size = vocab_size self.hidden_size = hidden_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.intermediate_size = intermediate_size self.hidden_act = hidden_act self.hidden_dropout_prob = hidden_dropout_prob self.attention_probs_dropout_prob = attention_probs_dropout_prob self.max_position_embeddings = max_position_embeddings self.type_vocab_size = type_vocab_size self.type_sequence_label_size = type_sequence_label_size self.initializer_range = initializer_range self.num_labels = num_labels self.num_choices = num_choices self.scope = scope def prepare_config_and_inputs(self): input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) input_mask = None if self.use_input_mask: input_mask = random_attention_mask([self.batch_size, self.seq_length]) sequence_labels = None token_labels = None choice_labels = None if self.use_labels: sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size) token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels) choice_labels = ids_tensor([self.batch_size], self.num_choices) config = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def get_config(self): return DistilBertConfig( vocab_size=self.vocab_size, dim=self.hidden_size, n_layers=self.num_hidden_layers, n_heads=self.num_attention_heads, hidden_dim=self.intermediate_size, hidden_act=self.hidden_act, dropout=self.hidden_dropout_prob, attention_dropout=self.attention_probs_dropout_prob, max_position_embeddings=self.max_position_embeddings, initializer_range=self.initializer_range, ) def create_and_check_distilbert_model( self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels ): model = DistilBertModel(config=config) model.to(torch_device) model.eval() result = model(input_ids, input_mask) result = model(input_ids) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) def create_and_check_distilbert_for_masked_lm( self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels ): model = DistilBertForMaskedLM(config=config) model.to(torch_device) model.eval() result = model(input_ids, attention_mask=input_mask, labels=token_labels) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size)) def create_and_check_distilbert_for_question_answering( self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels ): model = DistilBertForQuestionAnswering(config=config) model.to(torch_device) model.eval() result = model( input_ids, attention_mask=input_mask, start_positions=sequence_labels, end_positions=sequence_labels ) self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length)) self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length)) def create_and_check_distilbert_for_sequence_classification( self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels ): config.num_labels = self.num_labels model = DistilBertForSequenceClassification(config) model.to(torch_device) model.eval() result = model(input_ids, attention_mask=input_mask, labels=sequence_labels) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels)) def create_and_check_distilbert_for_token_classification( self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels ): config.num_labels = self.num_labels model = DistilBertForTokenClassification(config=config) model.to(torch_device) model.eval() result = model(input_ids, attention_mask=input_mask, labels=token_labels) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels)) def create_and_check_distilbert_for_multiple_choice( self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels ): config.num_choices = self.num_choices model = DistilBertForMultipleChoice(config=config) model.to(torch_device) model.eval() multiple_choice_inputs_ids = input_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous() multiple_choice_input_mask = input_mask.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous() result = model( multiple_choice_inputs_ids, attention_mask=multiple_choice_input_mask, labels=choice_labels, ) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_choices)) def prepare_config_and_inputs_for_common(self): config_and_inputs = self.prepare_config_and_inputs() (config, input_ids, input_mask, sequence_labels, token_labels, choice_labels) = config_and_inputs inputs_dict = {"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch
DistilBertModelTester
python
dagster-io__dagster
python_modules/dagster/dagster/_core/instance/config.py
{ "start": 23890, "end": 23959 }
class ____(Enum): OP = "op" RUN = "run" @record
PoolGranularity
python
conda__conda
conda/testing/integration.py
{ "start": 1326, "end": 3807 }
class ____: COMPARE = "compare" CONFIG = "config" CLEAN = "clean" CREATE = "create" INFO = "info" INSTALL = "install" LIST = "list" REMOVE = "remove" SEARCH = "search" UPDATE = "update" RUN = "run" def package_is_installed( prefix: str | os.PathLike | Path, spec: str | MatchSpec, reload_records: bool = True, ) -> PrefixRecord | None: spec = MatchSpec(spec) prefix_data = PrefixData(prefix, interoperability=True) if reload_records: prefix_data.load() prefix_recs = tuple(prefix_data.query(spec)) if not prefix_recs: return None elif len(prefix_recs) > 1: raise AssertionError( f"Multiple packages installed.{dashlist(prec.dist_str() for prec in prefix_recs)}" ) else: return prefix_recs[0] def get_shortcut_dir(prefix_for_unix=sys.prefix): if sys.platform == "win32": # On Windows, .nonadmin has been historically created by constructor in sys.prefix user_mode = "user" if Path(sys.prefix, ".nonadmin").is_file() else "system" try: # menuinst v2 from menuinst.platforms.win_utils.knownfolders import dirs_src return dirs_src[user_mode]["start"][0] except ImportError: # older menuinst versions; TODO: remove try: from menuinst.win32 import dirs_src return dirs_src[user_mode]["start"][0] except ImportError: from menuinst.win32 import dirs return dirs[user_mode]["start"] # on unix, .nonadmin is only created by menuinst v2 as needed on the target prefix # it might exist, or might not; if it doesn't, we try to create it # see https://github.com/conda/menuinst/issues/150 non_admin_file = Path(prefix_for_unix, ".nonadmin") if non_admin_file.is_file(): user_mode = "user" else: try: non_admin_file.touch() except OSError: user_mode = "system" else: user_mode = "user" non_admin_file.unlink() if sys.platform == "darwin": if user_mode == "user": return join(os.environ["HOME"], "Applications") return "/Applications" if sys.platform == "linux": if user_mode == "user": return join(os.environ["HOME"], ".local", "share", "applications") return "/usr/share/applications" raise NotImplementedError(sys.platform)
Commands
python
wandb__wandb
wandb/automations/_generated/get_automations_by_entity.py
{ "start": 370, "end": 478 }
class ____(GQLResult): projects: Optional[GetAutomationsByEntityScopeProjects]
GetAutomationsByEntityScope
python
run-llama__llama_index
llama-index-integrations/evaluation/llama-index-evaluation-tonic-validate/llama_index/evaluation/tonic_validate/answer_consistency_binary.py
{ "start": 371, "end": 2023 }
class ____(BaseEvaluator): """ Tonic Validate's answer consistency binary metric. The output score is a float that is either 0.0 or 1.0. See https://docs.tonic.ai/validate/ for more details. Args: openai_service(OpenAIService): The OpenAI service to use. Specifies the chat completion model to use as the LLM evaluator. Defaults to "gpt-4". """ def __init__(self, openai_service: Optional[Any] = None): if openai_service is None: openai_service = OpenAIService("gpt-4") self.openai_service = openai_service self.metric = AnswerConsistencyBinaryMetric() async def aevaluate( self, query: Optional[str] = None, response: Optional[str] = None, contexts: Optional[Sequence[str]] = None, **kwargs: Any, ) -> EvaluationResult: from tonic_validate.classes.benchmark import BenchmarkItem from tonic_validate.classes.llm_response import LLMResponse benchmark_item = BenchmarkItem(question=query) llm_response = LLMResponse( llm_answer=response, llm_context_list=contexts, benchmark_item=benchmark_item, ) score = self.metric.score(llm_response, self.openai_service) return EvaluationResult( query=query, contexts=contexts, response=response, score=score ) def _get_prompts(self) -> PromptDictType: return {} def _get_prompt_modules(self) -> PromptMixinType: return {} def _update_prompts(self, prompts_dict: PromptDictType) -> None: return
AnswerConsistencyBinaryEvaluator
python
dagster-io__dagster
python_modules/dagster/dagster_tests/core_tests/hook_tests/test_hook_run.py
{ "start": 290, "end": 19136 }
class ____(Exception): pass @dg.resource def resource_a(_init_context): return 1 def test_hook_on_op_instance(): called_hook_to_ops = defaultdict(set) @event_list_hook(required_resource_keys={"resource_a"}) def a_hook(context, _): called_hook_to_ops[context.hook_def.name].add(context.op.name) assert context.resources.resource_a == 1 return HookExecutionResult("a_hook") @dg.op def a_op(_): pass @dg.job(resource_defs={"resource_a": resource_a}) def a_job(): a_op.with_hooks(hook_defs={a_hook})() a_op.alias("op_with_hook").with_hooks(hook_defs={a_hook})() a_op.alias("op_without_hook")() result = a_job.execute_in_process() assert result.success assert called_hook_to_ops["a_hook"] == {"a_op", "op_with_hook"} def test_hook_accumulation(): called_hook_to_step_keys = defaultdict(set) @event_list_hook def job_hook(context, _): called_hook_to_step_keys[context.hook_def.name].add(context.step_key) return HookExecutionResult("job_hook") @event_list_hook def op_1_hook(context, _): called_hook_to_step_keys[context.hook_def.name].add(context.step_key) return HookExecutionResult("op_1_hook") @event_list_hook def graph_1_hook(context, _): called_hook_to_step_keys[context.hook_def.name].add(context.step_key) return HookExecutionResult("graph_1_hook") @dg.op def op_1(_): return 1 @dg.op def op_2(_, num): return num @dg.op def op_3(_): return 1 @dg.graph def graph_1(): return op_2(op_1.with_hooks({op_1_hook})()) @dg.graph def graph_2(): op_3() return graph_1.with_hooks({graph_1_hook})() @job_hook @dg.job def a_job(): graph_2() result = a_job.execute_in_process() assert result.success # make sure we gather hooks from all places and invoke them with the right steps assert called_hook_to_step_keys == { "job_hook": { "graph_2.graph_1.op_1", "graph_2.graph_1.op_2", "graph_2.op_3", }, "op_1_hook": {"graph_2.graph_1.op_1"}, "graph_1_hook": { "graph_2.graph_1.op_1", "graph_2.graph_1.op_2", }, } def test_hook_on_graph_instance(): called_hook_to_step_keys = defaultdict(set) @event_list_hook def hook_a_generic(context, _): called_hook_to_step_keys[context.hook_def.name].add(context.step_key) return HookExecutionResult("hook_a_generic") @dg.op def two(_): return 1 @dg.op def add_one(_, num): return num + 1 @dg.graph def add_two(): adder_1 = add_one.alias("adder_1") adder_2 = add_one.alias("adder_2") return adder_2(adder_1(two())) @dg.job def a_job(): add_two.with_hooks({hook_a_generic})() result = a_job.execute_in_process() assert result.success # the hook should run on all steps inside a graph assert called_hook_to_step_keys["hook_a_generic"] == set( [i.step_key for i in result.filter_events(lambda i: i.is_step_event)] ) def test_success_hook_on_op_instance(): called_hook_to_ops = defaultdict(set) @dg.success_hook(required_resource_keys={"resource_a"}) def a_hook(context): called_hook_to_ops[context.hook_def.name].add(context.op.name) assert context.resources.resource_a == 1 @dg.op def a_op(_): pass @dg.op def failed_op(_): raise SomeUserException() @dg.job(resource_defs={"resource_a": resource_a}) def a_job(): a_op.with_hooks(hook_defs={a_hook})() a_op.alias("op_with_hook").with_hooks(hook_defs={a_hook})() a_op.alias("op_without_hook")() failed_op.with_hooks(hook_defs={a_hook})() result = a_job.execute_in_process(raise_on_error=False) assert not result.success assert called_hook_to_ops["a_hook"] == {"a_op", "op_with_hook"} def test_success_hook_on_op_instance_subset(): called_hook_to_ops = defaultdict(set) @dg.success_hook(required_resource_keys={"resource_a"}) def a_hook(context): called_hook_to_ops[context.hook_def.name].add(context.op.name) assert context.resources.resource_a == 1 @dg.op def a_op(_): pass @dg.op def failed_op(_): raise SomeUserException() @dg.job(resource_defs={"resource_a": resource_a}) def a_job(): a_op.with_hooks(hook_defs={a_hook})() a_op.alias("op_with_hook").with_hooks(hook_defs={a_hook})() a_op.alias("op_without_hook")() failed_op.with_hooks(hook_defs={a_hook})() result = a_job.execute_in_process(raise_on_error=False, op_selection=["a_op", "op_with_hook"]) assert result.success assert called_hook_to_ops["a_hook"] == {"a_op", "op_with_hook"} def test_failure_hook_on_op_instance(): called_hook_to_ops = defaultdict(set) @dg.failure_hook(required_resource_keys={"resource_a"}) def a_hook(context): called_hook_to_ops[context.hook_def.name].add(context.op.name) assert context.resources.resource_a == 1 @dg.op def failed_op(_): raise SomeUserException() @dg.op def a_succeeded_op(_): pass @dg.job(resource_defs={"resource_a": resource_a}) def a_job(): failed_op.with_hooks(hook_defs={a_hook})() failed_op.alias("op_with_hook").with_hooks(hook_defs={a_hook})() failed_op.alias("op_without_hook")() a_succeeded_op.with_hooks(hook_defs={a_hook})() result = a_job.execute_in_process(raise_on_error=False) assert not result.success assert called_hook_to_ops["a_hook"] == {"failed_op", "op_with_hook"} def test_failure_hook_op_exception(): called = {} @dg.failure_hook def a_hook(context): called[context.op.name] = context.op_exception @dg.op def a_op(_): pass @dg.op def user_code_error_op(_): raise SomeUserException() @dg.op def failure_op(_): raise dg.Failure() @a_hook @dg.job def a_job(): a_op() user_code_error_op() failure_op() result = a_job.execute_in_process(raise_on_error=False) assert not result.success assert "a_op" not in called assert isinstance(called.get("user_code_error_op"), SomeUserException) assert isinstance(called.get("failure_op"), dg.Failure) def test_none_op_exception_access(): called = {} @dg.success_hook def a_hook(context): called[context.op.name] = context.op_exception @dg.op def a_op(_): pass @a_hook @dg.job def a_job(): a_op() result = a_job.execute_in_process(raise_on_error=False) assert result.success assert called.get("a_op") is None def test_op_outputs_access(): called = {} @dg.success_hook def my_success_hook(context): called[context.step_key] = context.op_output_values @dg.failure_hook def my_failure_hook(context): called[context.step_key] = context.op_output_values @dg.op(out={"one": dg.Out(), "two": dg.Out(), "three": dg.Out()}) def a_op(_): yield dg.Output(1, "one") yield dg.Output(2, "two") yield dg.Output(3, "three") @dg.op(out={"one": dg.Out(), "two": dg.Out()}) def failed_op(_): yield dg.Output(1, "one") raise SomeUserException() yield dg.Output(3, "two") @dg.op(out=dg.DynamicOut()) def dynamic_op(_): yield dg.DynamicOutput(1, mapping_key="mapping_1") yield dg.DynamicOutput(2, mapping_key="mapping_2") @dg.op def echo(_, x): return x @my_success_hook @my_failure_hook @dg.job def a_job(): a_op() failed_op() dynamic_op().map(echo) result = a_job.execute_in_process(raise_on_error=False) assert not result.success assert called.get("a_op") == {"one": 1, "two": 2, "three": 3} assert called.get("failed_op") == {"one": 1} assert called.get("dynamic_op") == {"result": {"mapping_1": 1, "mapping_2": 2}} assert called.get("echo[mapping_1]") == {"result": 1} assert called.get("echo[mapping_2]") == {"result": 2} def test_op_metadata_access(): """Test that HookContext op_output_metadata is successfully populated upon both Output(value, metadata) and context.add_output_metadata(metadata) calls.""" called = {} @dg.success_hook def my_success_hook(context): called[context.step_key] = context.op_output_metadata @dg.op(out={"one": dg.Out(), "two": dg.Out(), "three": dg.Out()}) def output_metadata_op(_): yield dg.Output(1, "one", metadata={"foo": "bar"}) yield dg.Output(2, "two", metadata={"baz": "qux"}) yield dg.Output(3, "three", metadata={"quux": "quuz"}) @dg.op() def context_metadata_op(context: OpExecutionContext): context.add_output_metadata(metadata={"foo": "bar"}) yield dg.Output(value=1) @my_success_hook @dg.job def metadata_job(): output_metadata_op() context_metadata_op() result = metadata_job.execute_in_process(raise_on_error=False) assert result.success assert called.get("context_metadata_op") == { "result": {"foo": dg.TextMetadataValue(text="bar")} } assert called.get("output_metadata_op") == { "one": {"foo": dg.TextMetadataValue(text="bar")}, "two": {"baz": dg.TextMetadataValue(text="qux")}, "three": {"quux": dg.TextMetadataValue(text="quuz")}, } def test_hook_on_job_def(): called_hook_to_ops = defaultdict(set) @event_list_hook def hook_a_generic(context, _): called_hook_to_ops[context.hook_def.name].add(context.op.name) return HookExecutionResult("hook_a_generic") @event_list_hook def hook_b_generic(context, _): called_hook_to_ops[context.hook_def.name].add(context.op.name) return HookExecutionResult("hook_b_generic") @dg.op def op_a(_): pass @dg.op def op_b(_): pass @dg.op def op_c(_): pass @dg.job(hooks={hook_b_generic}) def a_job(): op_a() op_b() op_c() result = a_job.with_hooks({hook_a_generic}).execute_in_process() assert result.success # the hook should run on all ops assert called_hook_to_ops == { "hook_b_generic": {"op_b", "op_a", "op_c"}, "hook_a_generic": {"op_b", "op_a", "op_c"}, } def test_hook_on_job_def_with_graphs(): called_hook_to_step_keys = defaultdict(set) @event_list_hook def hook_a_generic(context, _): called_hook_to_step_keys[context.hook_def.name].add(context.step_key) return HookExecutionResult("hook_a_generic") @dg.op def two(_): return 1 @dg.op def add_one(_, num): return num + 1 @dg.graph def add_two(): adder_1 = add_one.alias("adder_1") adder_2 = add_one.alias("adder_2") return adder_2(adder_1(two())) @dg.job def a_job(): add_two() hooked_job = a_job.with_hooks({hook_a_generic}) # hooked_job should be a copy of the original job assert hooked_job.all_node_defs == a_job.all_node_defs result = hooked_job.execute_in_process() assert result.success # the hook should run on all steps assert called_hook_to_step_keys["hook_a_generic"] == set( [i.step_key for i in result.filter_events(lambda i: i.is_step_event)] ) def test_hook_decorate_job_def(): called_hook_to_ops = defaultdict(set) @event_list_hook def hook_a_generic(context, _): called_hook_to_ops[context.hook_def.name].add(context.op.name) return HookExecutionResult("hook_a_generic") @dg.success_hook def hook_b_success(context): called_hook_to_ops[context.hook_def.name].add(context.op.name) @dg.failure_hook def hook_c_failure(context): called_hook_to_ops[context.hook_def.name].add(context.op.name) @dg.op def op_a(_): pass @dg.op def op_b(_): pass @dg.op def failed_op(_): raise SomeUserException() @hook_c_failure @hook_b_success @hook_a_generic @dg.job def a_job(): op_a() failed_op() op_b() result = a_job.execute_in_process(raise_on_error=False) assert not result.success # a generic hook runs on all ops assert called_hook_to_ops["hook_a_generic"] == { "op_a", "op_b", "failed_op", } # a success hook runs on all succeeded ops assert called_hook_to_ops["hook_b_success"] == {"op_a", "op_b"} # a failure hook runs on all failed ops assert called_hook_to_ops["hook_c_failure"] == {"failed_op"} def test_hook_on_job_def_and_op_instance(): called_hook_to_ops = defaultdict(set) @event_list_hook def hook_a_generic(context, _): called_hook_to_ops[context.hook_def.name].add(context.op.name) return HookExecutionResult("hook_a_generic") @dg.success_hook def hook_b_success(context): called_hook_to_ops[context.hook_def.name].add(context.op.name) @dg.failure_hook def hook_c_failure(context): called_hook_to_ops[context.hook_def.name].add(context.op.name) @dg.op def op_a(_): pass @dg.op def op_b(_): pass @dg.op def failed_op(_): raise SomeUserException() @hook_a_generic @dg.job def a_job(): op_a.with_hooks({hook_b_success})() failed_op.with_hooks({hook_c_failure})() # "hook_a_generic" should run on "op_b" only once op_b.with_hooks({hook_a_generic})() result = a_job.execute_in_process(raise_on_error=False) assert not result.success # a generic hook runs on all ops assert called_hook_to_ops["hook_a_generic"] == { "op_a", "op_b", "failed_op", } # a success hook runs on "op_a" assert called_hook_to_ops["hook_b_success"] == {"op_a"} # a failure hook runs on "failed_op" assert called_hook_to_ops["hook_c_failure"] == {"failed_op"} hook_events = result.filter_events(lambda event: event.is_hook_event) # same hook will run once on the same op invocation assert len(hook_events) == 5 def test_hook_context_config_schema(): called_hook_to_ops = defaultdict(set) @event_list_hook def a_hook(context, _): called_hook_to_ops[context.hook_def.name].add(context.op.name) assert context.op_config == {"config_1": 1} return HookExecutionResult("a_hook") @dg.op(config_schema={"config_1": dg.Int}) def a_op(_): pass @dg.job def a_job(): a_op.with_hooks(hook_defs={a_hook})() result = a_job.execute_in_process(run_config={"ops": {"a_op": {"config": {"config_1": 1}}}}) assert result.success assert called_hook_to_ops["a_hook"] == {"a_op"} def test_hook_resource_mismatch(): @event_list_hook(required_resource_keys={"b"}) def a_hook(context, _): assert context.resources.resource_a == 1 return HookExecutionResult("a_hook") @dg.op def a_op(_): pass with pytest.raises( dg.DagsterInvalidDefinitionError, match=( "resource with key 'b' required by hook 'a_hook' attached to job '_' was not provided" ), ): @a_hook @dg.job(resource_defs={"a": resource_a}) def _(): a_op() with pytest.raises( dg.DagsterInvalidDefinitionError, match=( "resource with key 'b' required by hook 'a_hook' attached to op 'a_op' was not provided" ), ): @dg.job(resource_defs={"a": resource_a}) def _(): a_op.with_hooks({a_hook})() def test_hook_subjob(): called_hook_to_ops = defaultdict(set) @event_list_hook def hook_a_generic(context, _): called_hook_to_ops[context.hook_def.name].add(context.op.name) return HookExecutionResult("hook_a_generic") @dg.op def op_a(_): pass @dg.op def op_b(_): pass @hook_a_generic @dg.job def a_job(): op_a() op_b() result = a_job.execute_in_process() assert result.success # a generic hook runs on all ops assert called_hook_to_ops["hook_a_generic"] == {"op_a", "op_b"} called_hook_to_ops = defaultdict(set) result = a_job.execute_in_process(op_selection=["op_a"]) assert result.success assert called_hook_to_ops["hook_a_generic"] == {"op_a"} def test_hook_ops(): called_hook_to_ops = defaultdict(set) @dg.success_hook def my_hook(context): called_hook_to_ops[context.hook_def.name].add(context.op.name) return HookExecutionResult("my_hook") @dg.op def a_op(_): pass @dg.graph def a_graph(): a_op.with_hooks(hook_defs={my_hook})() a_op.alias("op_with_hook").with_hooks(hook_defs={my_hook})() a_op.alias("op_without_hook")() result = a_graph.execute_in_process() assert result.success assert called_hook_to_ops["my_hook"] == {"a_op", "op_with_hook"} def test_hook_graph(): called_hook_to_ops = defaultdict(set) @dg.success_hook def a_hook(context): called_hook_to_ops[context.hook_def.name].add(context.op.name) return HookExecutionResult("a_hook") @dg.success_hook def b_hook(context): called_hook_to_ops[context.hook_def.name].add(context.op.name) return HookExecutionResult("a_hook") @dg.op def a_op(_): pass @dg.op def b_op(_): pass @a_hook @dg.graph def sub_graph(): a_op() @b_hook @dg.graph def super_graph(): sub_graph() b_op() result = super_graph.execute_in_process() assert result.success assert called_hook_to_ops["a_hook"] == {"a_op"} assert called_hook_to_ops["b_hook"] == {"a_op", "b_op"} # test to_job called_hook_to_ops = defaultdict(set) result = super_graph.to_job().execute_in_process() assert result.success assert called_hook_to_ops["a_hook"] == {"a_op"} assert called_hook_to_ops["b_hook"] == {"a_op", "b_op"} def test_hook_on_job(): called_hook_to_ops = defaultdict(set) @dg.success_hook def a_hook(context): called_hook_to_ops[context.hook_def.name].add(context.op.name) return HookExecutionResult("a_hook") @dg.op def basic(): return 5 @a_hook @dg.job def hooked_job(): basic() basic() basic() result = hooked_job.execute_in_process() assert result.success assert called_hook_to_ops["a_hook"] == {"basic", "basic_2", "basic_3"}
SomeUserException
python
scipy__scipy
benchmarks/benchmarks/go_benchmark_functions/go_funcs_B.py
{ "start": 9922, "end": 11257 }
class ____(Benchmark): r""" Bohachevsky 2 objective function. The Bohachevsky 2 [1]_ global optimization problem is a multimodal minimization problem defined as follows .. math:: f_{\text{Bohachevsky}}(x) = \sum_{i=1}^{n-1}\left[x_i^2 + 2 x_{i+1}^2 - 0.3 \cos(3 \pi x_i) - 0.4 \cos(4 \pi x_{i + 1}) + 0.7 \right] Here, :math:`n` represents the number of dimensions and :math:`x_i \in [-15, 15]` for :math:`i = 1, ..., n`. *Global optimum*: :math:`f(x) = 0` for :math:`x_i = 0` for :math:`i = 1, ..., n` .. [1] Jamil, M. & Yang, X.-S. A Literature Survey of Benchmark Functions For Global Optimization Problems Int. Journal of Mathematical Modelling and Numerical Optimisation, 2013, 4, 150-194. TODO: equation needs to be fixed up in the docstring. Jamil is also wrong. There should be no 0.4 factor in front of the cos term """ def __init__(self, dimensions=2): Benchmark.__init__(self, dimensions) self._bounds = list(zip([-100.0] * self.N, [100.0] * self.N)) self.global_optimum = [[0 for _ in range(self.N)]] self.fglob = 0.0 def fun(self, x, *args): self.nfev += 1 return (x[0] ** 2 + 2 * x[1] ** 2 - 0.3 * cos(3 * pi * x[0]) * cos(4 * pi * x[1]) + 0.3)
Bohachevsky2
python
gevent__gevent
src/gevent/tests/test__core.py
{ "start": 486, "end": 3249 }
class ____(object): kind = None def _makeOne(self): return self.kind(default=False) # pylint:disable=not-callable def destroyOne(self, loop): loop.destroy() def setUp(self): self.loop = self._makeOne() self.core = sys.modules[self.kind.__module__] def tearDown(self): self.destroyOne(self.loop) del self.loop def test_get_version(self): version = self.core.get_version() # pylint: disable=no-member self.assertIsInstance(version, str) self.assertTrue(version) header_version = self.core.get_header_version() # pylint: disable=no-member self.assertIsInstance(header_version, str) self.assertTrue(header_version) self.assertEqual(version, header_version) def test_events_conversion(self): self.assertEqual(self.core._events_to_str(self.core.READ | self.core.WRITE), # pylint: disable=no-member 'READ|WRITE') def test_EVENTS(self): self.assertEqual(str(self.core.EVENTS), # pylint: disable=no-member 'gevent.core.EVENTS') self.assertEqual(repr(self.core.EVENTS), # pylint: disable=no-member 'gevent.core.EVENTS') def test_io(self): if greentest.WIN: # libev raises IOError, libuv raises ValueError Error = (IOError, ValueError) else: Error = ValueError with self.assertRaises(Error): self.loop.io(-1, 1) if hasattr(self.core, 'TIMER'): # libev with self.assertRaises(ValueError): self.loop.io(1, self.core.TIMER) # pylint:disable=no-member # Test we can set events and io before it's started if not greentest.WIN: # We can't do this with arbitrary FDs on windows; # see libev_vfd.h io = self.loop.io(1, self.core.READ) # pylint:disable=no-member io.fd = 2 self.assertEqual(io.fd, 2) io.events = self.core.WRITE # pylint:disable=no-member if not hasattr(self.core, 'libuv'): # libev # pylint:disable=no-member self.assertEqual(self.core._events_to_str(io.events), 'WRITE|_IOFDSET') else: self.assertEqual(self.core._events_to_str(io.events), # pylint:disable=no-member 'WRITE') io.start(lambda: None) io.close() def test_timer_constructor(self): with self.assertRaises(ValueError): self.loop.timer(1, -1) def test_signal_constructor(self): with self.assertRaises(ValueError): self.loop.signal(1000)
WatcherTestMixin
python
getsentry__sentry
src/sentry/issues/endpoints/event_owners.py
{ "start": 562, "end": 2185 }
class ____(ProjectEndpoint): owner = ApiOwner.ISSUES publish_status = { "GET": ApiPublishStatus.PRIVATE, } def get(self, request: Request, project, event_id) -> Response: """ Retrieve suggested owners information for an event `````````````````````````````````````````````````` :pparam string project_id_or_slug: the id or slug of the project the event belongs to. :pparam string event_id: the id of the event. :auth: required """ event = eventstore.backend.get_event_by_id(project.id, event_id) if event is None: return Response({"detail": "Event not found"}, status=404) owners, rules = ProjectOwnership.get_owners(project.id, event.data) serialized_owners = serialize(Actor.resolve_many(owners), request.user, ActorSerializer()) # Make sure the serialized owners are in the correct order ordered_owners = [] owner_by_id = {(o["id"], o["type"]): o for o in serialized_owners} for o in owners: key = (str(o.id), "team" if o.is_team else "user") if owner_by_id.get(key): ordered_owners.append(owner_by_id[key]) return Response( { "owners": ordered_owners, # TODO(mattrobenolt): We need to change the API here to return # all rules, just keeping this way currently for API compat "rule": rules[0].matcher if rules else None, "rules": rules or [], } )
EventOwnersEndpoint
python
huggingface__transformers
tests/models/speecht5/test_modeling_speecht5.py
{ "start": 71596, "end": 75091 }
class ____(ModelTesterMixin, unittest.TestCase): all_model_classes = (SpeechT5HifiGan,) if is_torch_available() else () test_resize_embeddings = False test_resize_position_embeddings = False test_mismatched_shapes = False test_missing_keys = False is_encoder_decoder = False has_attentions = False def setUp(self): self.model_tester = SpeechT5HifiGanTester(self) self.config_tester = ConfigTester(self, config_class=SpeechT5HifiGanConfig) def test_config(self): self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_from_and_save_pretrained_subfolder() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def test_model(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*config_and_inputs) def test_forward_signature(self): config, _ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: model = model_class(config) signature = inspect.signature(model.forward) # signature.parameters is an OrderedDict => so arg_names order is deterministic arg_names = [*signature.parameters.keys()] expected_arg_names = [ "spectrogram", ] self.assertListEqual(arg_names[: len(expected_arg_names)], expected_arg_names) @unittest.skip(reason="Model does not output hidden states") def test_hidden_states_output(self): pass @unittest.skip(reason="Model has no input_embeds") def test_inputs_embeds(self): pass @unittest.skip(reason="Model has no input_embeds") def test_model_get_set_embeddings(self): pass @unittest.skip(reason="Model does not support all arguments tested") def test_model_outputs_equivalence(self): pass @unittest.skip(reason="Model does not output hidden states") def test_retain_grad_hidden_states_attentions(self): pass def test_batched_inputs_outputs(self): config, inputs = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: model = model_class(config) model.to(torch_device) model.eval() batched_inputs = inputs["spectrogram"].unsqueeze(0).repeat(2, 1, 1) with torch.no_grad(): batched_outputs = model(batched_inputs.to(torch_device)) self.assertEqual( batched_inputs.shape[0], batched_outputs.shape[0], msg="Got different batch dims for input and output" ) def test_unbatched_inputs_outputs(self): config, inputs = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: model = model_class(config) model.to(torch_device) model.eval() with torch.no_grad(): outputs = model(inputs["spectrogram"].to(torch_device)) self.assertTrue(outputs.dim() == 1, msg="Got un-batched inputs but batched output")
SpeechT5HifiGanTest
python
jazzband__django-simple-history
simple_history/tests/models.py
{ "start": 4073, "end": 4316 }
class ____(models.Model): question = models.CharField(max_length=200) pub_date = models.DateTimeField("date published") places = models.ManyToManyField("Place") history = HistoricalRecords(m2m_fields=[places])
PollWithManyToMany
python
gevent__gevent
src/gevent/tests/test__hub.py
{ "start": 2657, "end": 2839 }
class ____(gevent.testing.timing.AbstractGenericWaitTestCase): def wait(self, timeout): gevent.sleep(timeout) def test_simple(self): gevent.sleep(0)
TestSleep
python
huggingface__transformers
src/transformers/models/metaclip_2/modeling_metaclip_2.py
{ "start": 40629, "end": 44248 }
class ____(MetaClip2PreTrainedModel): """ The vision model from MetaClip2 without any head or projection on top. This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.) This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior. Args: config ([`MetaClip2VisionConfig`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights. Examples: ```python >>> from PIL import Image >>> import requests >>> from transformers import AutoProcessor, MetaClip2VisionModel >>> model = MetaClip2VisionModel.from_pretrained("facebook/metaclip-2-worldwide-huge-quickgelu") >>> processor = AutoProcessor.from_pretrained("facebook/metaclip-2-worldwide-huge-quickgelu") >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg" >>> image = Image.open(requests.get(url, stream=True).raw) >>> inputs = processor(images=image, return_tensors="pt") >>> outputs = model(**inputs) >>> last_hidden_state = outputs.last_hidden_state >>> pooled_output = outputs.pooler_output # pooled CLS states ```""" config: MetaClip2VisionConfig main_input_name = "pixel_values" input_modalities = ("image",) _no_split_modules = ["MetaClip2EncoderLayer"] def __init__(self, config: MetaClip2VisionConfig): super().__init__(config) self.vision_model = MetaClip2VisionTransformer(config) # Initialize weights and apply final processing self.post_init() def get_input_embeddings(self) -> nn.Module: return self.vision_model.embeddings.patch_embedding @check_model_inputs(tie_last_hidden_states=False) @auto_docstring def forward( self, pixel_values: Optional[torch.FloatTensor] = None, interpolate_pos_encoding: bool = False, **kwargs: Unpack[TransformersKwargs], ) -> BaseModelOutputWithPooling: r""" Examples: ```python >>> from PIL import Image >>> import requests >>> from transformers import AutoProcessor, MetaClip2VisionModel >>> model = MetaClip2VisionModel.from_pretrained("facebook/metaclip-2-worldwide-huge-quickgelu") >>> processor = AutoProcessor.from_pretrained("facebook/metaclip-2-worldwide-huge-quickgelu") >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg" >>> image = Image.open(requests.get(url, stream=True).raw) >>> inputs = processor(images=image, return_tensors="pt") >>> outputs = model(**inputs) >>> last_hidden_state = outputs.last_hidden_state >>> pooled_output = outputs.pooler_output # pooled CLS states ```""" return self.vision_model( pixel_values=pixel_values, interpolate_pos_encoding=interpolate_pos_encoding, **kwargs, ) @dataclass @auto_docstring( custom_intro=""" Base class for vision model's outputs that also contains image embeddings of the pooling of the last hidden states. """ )
MetaClip2VisionModel
python
django__django
tests/model_fields/tests.py
{ "start": 426, "end": 486 }
class ____: class Field(models.Field): pass
Nested
python
getsentry__sentry
src/sentry/core/endpoints/scim/constants.py
{ "start": 1295, "end": 1390 }
class ____(str, Enum): ADD = "add" REMOVE = "remove" REPLACE = "replace"
TeamPatchOps
python
PrefectHQ__prefect
src/prefect/server/database/_migrations/versions/sqlite/2022_01_20_115236_9725c1cbee35_initial_migration.py
{ "start": 296, "end": 35404 }
class ____(PrefectBaseModel): """ DataDocuments were deprecated in September 2022 and this stub is included here to simplify removal from the library. """ encoding: str blob: bytes # revision identifiers, used by Alembic. revision = "9725c1cbee35" down_revision = None branch_labels = None depends_on = None def upgrade(): # Create tables op.create_table( "flow", sa.Column( "id", prefect.server.utilities.database.UUID(), server_default=sa.text( "(\n (\n lower(hex(randomblob(4))) \n || '-' \n " " || lower(hex(randomblob(2))) \n || '-4' \n ||" " substr(lower(hex(randomblob(2))),2) \n || '-' \n ||" " substr('89ab',abs(random()) % 4 + 1, 1) \n ||" " substr(lower(hex(randomblob(2))),2) \n || '-' \n ||" " lower(hex(randomblob(6)))\n )\n )" ), nullable=False, ), sa.Column( "created", prefect.server.utilities.database.Timestamp(timezone=True), server_default=sa.text("(strftime('%Y-%m-%d %H:%M:%f000', 'now'))"), nullable=False, ), sa.Column( "updated", prefect.server.utilities.database.Timestamp(timezone=True), server_default=sa.text("(strftime('%Y-%m-%d %H:%M:%f000', 'now'))"), nullable=False, ), sa.Column("name", sa.String(), nullable=False), sa.Column( "tags", prefect.server.utilities.database.JSON(astext_type=Text()), server_default="[]", nullable=False, ), sa.PrimaryKeyConstraint("id", name=op.f("pk_flow")), sa.UniqueConstraint("name", name=op.f("uq_flow__name")), ) op.create_index(op.f("ix_flow__updated"), "flow", ["updated"], unique=False) op.create_table( "log", sa.Column( "id", prefect.server.utilities.database.UUID(), server_default=sa.text( "(\n (\n lower(hex(randomblob(4))) \n || '-' \n " " || lower(hex(randomblob(2))) \n || '-4' \n ||" " substr(lower(hex(randomblob(2))),2) \n || '-' \n ||" " substr('89ab',abs(random()) % 4 + 1, 1) \n ||" " substr(lower(hex(randomblob(2))),2) \n || '-' \n ||" " lower(hex(randomblob(6)))\n )\n )" ), nullable=False, ), sa.Column( "created", prefect.server.utilities.database.Timestamp(timezone=True), server_default=sa.text("(strftime('%Y-%m-%d %H:%M:%f000', 'now'))"), nullable=False, ), sa.Column( "updated", prefect.server.utilities.database.Timestamp(timezone=True), server_default=sa.text("(strftime('%Y-%m-%d %H:%M:%f000', 'now'))"), nullable=False, ), sa.Column("name", sa.String(), nullable=False), sa.Column("level", sa.SmallInteger(), nullable=False), sa.Column( "flow_run_id", prefect.server.utilities.database.UUID(), nullable=False ), sa.Column( "task_run_id", prefect.server.utilities.database.UUID(), nullable=True ), sa.Column("message", sa.Text(), nullable=False), sa.Column( "timestamp", prefect.server.utilities.database.Timestamp(timezone=True), nullable=False, ), sa.PrimaryKeyConstraint("id", name=op.f("pk_log")), ) op.create_index(op.f("ix_log__flow_run_id"), "log", ["flow_run_id"], unique=False) op.create_index(op.f("ix_log__level"), "log", ["level"], unique=False) op.create_index(op.f("ix_log__task_run_id"), "log", ["task_run_id"], unique=False) op.create_index(op.f("ix_log__timestamp"), "log", ["timestamp"], unique=False) op.create_index(op.f("ix_log__updated"), "log", ["updated"], unique=False) op.create_table( "concurrency_limit", sa.Column( "id", prefect.server.utilities.database.UUID(), server_default=sa.text( "(\n (\n lower(hex(randomblob(4))) \n || '-' \n " " || lower(hex(randomblob(2))) \n || '-4' \n ||" " substr(lower(hex(randomblob(2))),2) \n || '-' \n ||" " substr('89ab',abs(random()) % 4 + 1, 1) \n ||" " substr(lower(hex(randomblob(2))),2) \n || '-' \n ||" " lower(hex(randomblob(6)))\n )\n )" ), nullable=False, ), sa.Column( "created", prefect.server.utilities.database.Timestamp(timezone=True), server_default=sa.text("(strftime('%Y-%m-%d %H:%M:%f000', 'now'))"), nullable=False, ), sa.Column( "updated", prefect.server.utilities.database.Timestamp(timezone=True), server_default=sa.text("(strftime('%Y-%m-%d %H:%M:%f000', 'now'))"), nullable=False, ), sa.Column("tag", sa.String(), nullable=False), sa.Column("concurrency_limit", sa.Integer(), nullable=False), sa.Column( "active_slots", prefect.server.utilities.database.JSON(astext_type=sa.Text()), server_default="[]", nullable=False, ), sa.PrimaryKeyConstraint("id", name=op.f("pk_concurrency_limit")), ) op.create_index( op.f("ix_concurrency_limit__tag"), "concurrency_limit", ["tag"], unique=True ) op.create_index( op.f("ix_concurrency_limit__updated"), "concurrency_limit", ["updated"], unique=False, ) op.create_table( "saved_search", sa.Column( "id", prefect.server.utilities.database.UUID(), server_default=sa.text( "(\n (\n lower(hex(randomblob(4))) \n || '-' \n " " || lower(hex(randomblob(2))) \n || '-4' \n ||" " substr(lower(hex(randomblob(2))),2) \n || '-' \n ||" " substr('89ab',abs(random()) % 4 + 1, 1) \n ||" " substr(lower(hex(randomblob(2))),2) \n || '-' \n ||" " lower(hex(randomblob(6)))\n )\n )" ), nullable=False, ), sa.Column( "created", prefect.server.utilities.database.Timestamp(timezone=True), server_default=sa.text("(strftime('%Y-%m-%d %H:%M:%f000', 'now'))"), nullable=False, ), sa.Column( "updated", prefect.server.utilities.database.Timestamp(timezone=True), server_default=sa.text("(strftime('%Y-%m-%d %H:%M:%f000', 'now'))"), nullable=False, ), sa.Column("name", sa.String(), nullable=False), sa.Column( "filters", prefect.server.utilities.database.JSON(astext_type=Text()), server_default="[]", nullable=False, ), sa.PrimaryKeyConstraint("id", name=op.f("pk_saved_search")), sa.UniqueConstraint("name", name=op.f("uq_saved_search__name")), ) op.create_index( op.f("ix_saved_search__updated"), "saved_search", ["updated"], unique=False ) op.create_table( "task_run_state_cache", sa.Column( "id", prefect.server.utilities.database.UUID(), server_default=sa.text( "(\n (\n lower(hex(randomblob(4))) \n || '-' \n " " || lower(hex(randomblob(2))) \n || '-4' \n ||" " substr(lower(hex(randomblob(2))),2) \n || '-' \n ||" " substr('89ab',abs(random()) % 4 + 1, 1) \n ||" " substr(lower(hex(randomblob(2))),2) \n || '-' \n ||" " lower(hex(randomblob(6)))\n )\n )" ), nullable=False, ), sa.Column( "created", prefect.server.utilities.database.Timestamp(timezone=True), server_default=sa.text("(strftime('%Y-%m-%d %H:%M:%f000', 'now'))"), nullable=False, ), sa.Column( "updated", prefect.server.utilities.database.Timestamp(timezone=True), server_default=sa.text("(strftime('%Y-%m-%d %H:%M:%f000', 'now'))"), nullable=False, ), sa.Column("cache_key", sa.String(), nullable=False), sa.Column( "cache_expiration", prefect.server.utilities.database.Timestamp(timezone=True), nullable=True, ), sa.Column( "task_run_state_id", prefect.server.utilities.database.UUID(), nullable=False, ), sa.PrimaryKeyConstraint("id", name=op.f("pk_task_run_state_cache")), ) op.create_index( "ix_task_run_state_cache__cache_key_created_desc", "task_run_state_cache", ["cache_key", sa.text("created DESC")], unique=False, ) op.create_index( op.f("ix_task_run_state_cache__updated"), "task_run_state_cache", ["updated"], unique=False, ) op.create_table( "deployment", sa.Column( "id", prefect.server.utilities.database.UUID(), server_default=sa.text( "(\n (\n lower(hex(randomblob(4))) \n || '-' \n " " || lower(hex(randomblob(2))) \n || '-4' \n ||" " substr(lower(hex(randomblob(2))),2) \n || '-' \n ||" " substr('89ab',abs(random()) % 4 + 1, 1) \n ||" " substr(lower(hex(randomblob(2))),2) \n || '-' \n ||" " lower(hex(randomblob(6)))\n )\n )" ), nullable=False, ), sa.Column( "created", prefect.server.utilities.database.Timestamp(timezone=True), server_default=sa.text("(strftime('%Y-%m-%d %H:%M:%f000', 'now'))"), nullable=False, ), sa.Column( "updated", prefect.server.utilities.database.Timestamp(timezone=True), server_default=sa.text("(strftime('%Y-%m-%d %H:%M:%f000', 'now'))"), nullable=False, ), sa.Column("name", sa.String(), nullable=False), sa.Column( "schedule", prefect.server.utilities.database.Pydantic( prefect.server.schemas.schedules.SCHEDULE_TYPES ), nullable=True, ), sa.Column( "is_schedule_active", sa.Boolean(), server_default="1", nullable=False ), sa.Column( "tags", prefect.server.utilities.database.JSON(astext_type=Text()), server_default="[]", nullable=False, ), sa.Column( "parameters", prefect.server.utilities.database.JSON(astext_type=Text()), server_default="{}", nullable=False, ), sa.Column( "flow_data", prefect.server.utilities.database.Pydantic(DataDocument), nullable=True, ), sa.Column("flow_runner_type", sa.String(), nullable=True), sa.Column( "flow_runner_config", prefect.server.utilities.database.JSON(astext_type=Text()), nullable=True, ), sa.Column("flow_id", prefect.server.utilities.database.UUID(), nullable=False), sa.ForeignKeyConstraint( ["flow_id"], ["flow.id"], name=op.f("fk_deployment__flow_id__flow"), ondelete="CASCADE", ), sa.PrimaryKeyConstraint("id", name=op.f("pk_deployment")), ) op.create_index( op.f("ix_deployment__flow_id"), "deployment", ["flow_id"], unique=False ) op.create_index( op.f("ix_deployment__updated"), "deployment", ["updated"], unique=False ) op.create_index( "uq_deployment__flow_id_name", "deployment", ["flow_id", "name"], unique=True ) op.create_table( "flow_run", sa.Column( "id", prefect.server.utilities.database.UUID(), server_default=sa.text( "(\n (\n lower(hex(randomblob(4))) \n || '-' \n " " || lower(hex(randomblob(2))) \n || '-4' \n ||" " substr(lower(hex(randomblob(2))),2) \n || '-' \n ||" " substr('89ab',abs(random()) % 4 + 1, 1) \n ||" " substr(lower(hex(randomblob(2))),2) \n || '-' \n ||" " lower(hex(randomblob(6)))\n )\n )" ), nullable=False, ), sa.Column( "created", prefect.server.utilities.database.Timestamp(timezone=True), server_default=sa.text("(strftime('%Y-%m-%d %H:%M:%f000', 'now'))"), nullable=False, ), sa.Column( "updated", prefect.server.utilities.database.Timestamp(timezone=True), server_default=sa.text("(strftime('%Y-%m-%d %H:%M:%f000', 'now'))"), nullable=False, ), sa.Column("name", sa.String(), nullable=False), sa.Column( "state_type", sa.Enum( "SCHEDULED", "PENDING", "RUNNING", "COMPLETED", "FAILED", "CANCELLED", name="state_type", ), nullable=True, ), sa.Column("run_count", sa.Integer(), server_default="0", nullable=False), sa.Column( "expected_start_time", prefect.server.utilities.database.Timestamp(timezone=True), nullable=True, ), sa.Column( "next_scheduled_start_time", prefect.server.utilities.database.Timestamp(timezone=True), nullable=True, ), sa.Column( "start_time", prefect.server.utilities.database.Timestamp(timezone=True), nullable=True, ), sa.Column( "end_time", prefect.server.utilities.database.Timestamp(timezone=True), nullable=True, ), sa.Column("total_run_time", sa.Interval(), server_default="0", nullable=False), sa.Column("flow_version", sa.String(), nullable=True), sa.Column( "parameters", prefect.server.utilities.database.JSON(astext_type=Text()), server_default="{}", nullable=False, ), sa.Column("idempotency_key", sa.String(), nullable=True), sa.Column( "context", prefect.server.utilities.database.JSON(astext_type=Text()), server_default="{}", nullable=False, ), sa.Column( "empirical_policy", prefect.server.utilities.database.JSON(astext_type=Text()), server_default="{}", nullable=False, ), sa.Column( "tags", prefect.server.utilities.database.JSON(astext_type=Text()), server_default="[]", nullable=False, ), sa.Column("flow_runner_type", sa.String(), nullable=True), sa.Column( "flow_runner_config", prefect.server.utilities.database.JSON(astext_type=Text()), nullable=True, ), sa.Column( "empirical_config", prefect.server.utilities.database.JSON(astext_type=Text()), server_default="{}", nullable=False, ), sa.Column("auto_scheduled", sa.Boolean(), server_default="0", nullable=False), sa.Column("flow_id", prefect.server.utilities.database.UUID(), nullable=False), sa.Column( "deployment_id", prefect.server.utilities.database.UUID(), nullable=True ), sa.Column( "parent_task_run_id", prefect.server.utilities.database.UUID(), nullable=True, ), sa.Column("state_id", prefect.server.utilities.database.UUID(), nullable=True), sa.ForeignKeyConstraint( ["deployment_id"], ["deployment.id"], name=op.f("fk_flow_run__deployment_id__deployment"), ondelete="set null", ), sa.ForeignKeyConstraint( ["flow_id"], ["flow.id"], name=op.f("fk_flow_run__flow_id__flow"), ondelete="cascade", ), sa.ForeignKeyConstraint( ["parent_task_run_id"], ["task_run.id"], name=op.f("fk_flow_run__parent_task_run_id__task_run"), ondelete="SET NULL", use_alter=True, ), sa.ForeignKeyConstraint( ["state_id"], ["flow_run_state.id"], name=op.f("fk_flow_run__state_id__flow_run_state"), ondelete="SET NULL", use_alter=True, ), sa.PrimaryKeyConstraint("id", name=op.f("pk_flow_run")), ) op.create_index( op.f("ix_flow_run__deployment_id"), "flow_run", ["deployment_id"], unique=False ) op.create_index( "ix_flow_run__end_time_desc", "flow_run", [sa.text("end_time DESC")], unique=False, ) op.create_index( "ix_flow_run__expected_start_time_desc", "flow_run", [sa.text("expected_start_time DESC")], unique=False, ) op.create_index(op.f("ix_flow_run__flow_id"), "flow_run", ["flow_id"], unique=False) op.create_index( op.f("ix_flow_run__flow_version"), "flow_run", ["flow_version"], unique=False ) op.create_index(op.f("ix_flow_run__name"), "flow_run", ["name"], unique=False) op.create_index( "ix_flow_run__next_scheduled_start_time_asc", "flow_run", [sa.text("next_scheduled_start_time ASC")], unique=False, ) op.create_index( op.f("ix_flow_run__parent_task_run_id"), "flow_run", ["parent_task_run_id"], unique=False, ) op.create_index("ix_flow_run__start_time", "flow_run", ["start_time"], unique=False) op.create_index( op.f("ix_flow_run__state_id"), "flow_run", ["state_id"], unique=False ) op.create_index("ix_flow_run__state_type", "flow_run", ["state_type"], unique=False) op.create_index(op.f("ix_flow_run__updated"), "flow_run", ["updated"], unique=False) op.create_index( "uq_flow_run__flow_id_idempotency_key", "flow_run", ["flow_id", "idempotency_key"], unique=True, ) op.create_table( "flow_run_state", sa.Column( "id", prefect.server.utilities.database.UUID(), server_default=sa.text( "(\n (\n lower(hex(randomblob(4))) \n || '-' \n " " || lower(hex(randomblob(2))) \n || '-4' \n ||" " substr(lower(hex(randomblob(2))),2) \n || '-' \n ||" " substr('89ab',abs(random()) % 4 + 1, 1) \n ||" " substr(lower(hex(randomblob(2))),2) \n || '-' \n ||" " lower(hex(randomblob(6)))\n )\n )" ), nullable=False, ), sa.Column( "created", prefect.server.utilities.database.Timestamp(timezone=True), server_default=sa.text("(strftime('%Y-%m-%d %H:%M:%f000', 'now'))"), nullable=False, ), sa.Column( "updated", prefect.server.utilities.database.Timestamp(timezone=True), server_default=sa.text("(strftime('%Y-%m-%d %H:%M:%f000', 'now'))"), nullable=False, ), sa.Column( "type", sa.Enum( "SCHEDULED", "PENDING", "RUNNING", "COMPLETED", "FAILED", "CANCELLED", name="state_type", ), nullable=False, ), sa.Column( "timestamp", prefect.server.utilities.database.Timestamp(timezone=True), server_default=sa.text("(strftime('%Y-%m-%d %H:%M:%f000', 'now'))"), nullable=False, ), sa.Column("name", sa.String(), nullable=False), sa.Column("message", sa.String(), nullable=True), sa.Column( "state_details", prefect.server.utilities.database.Pydantic( prefect.server.schemas.states.StateDetails ), server_default="{}", nullable=False, ), sa.Column( "data", prefect.server.utilities.database.Pydantic(DataDocument), nullable=True, ), sa.Column( "flow_run_id", prefect.server.utilities.database.UUID(), nullable=False ), sa.ForeignKeyConstraint( ["flow_run_id"], ["flow_run.id"], name=op.f("fk_flow_run_state__flow_run_id__flow_run"), ondelete="cascade", ), sa.PrimaryKeyConstraint("id", name=op.f("pk_flow_run_state")), ) op.create_index( op.f("ix_flow_run_state__name"), "flow_run_state", ["name"], unique=False ) op.create_index( op.f("ix_flow_run_state__type"), "flow_run_state", ["type"], unique=False ) op.create_index( op.f("ix_flow_run_state__updated"), "flow_run_state", ["updated"], unique=False ) op.create_index( "uq_flow_run_state__flow_run_id_timestamp_desc", "flow_run_state", ["flow_run_id", sa.text("timestamp DESC")], unique=True, ) op.create_table( "task_run", sa.Column( "id", prefect.server.utilities.database.UUID(), server_default=sa.text( "(\n (\n lower(hex(randomblob(4))) \n || '-' \n " " || lower(hex(randomblob(2))) \n || '-4' \n ||" " substr(lower(hex(randomblob(2))),2) \n || '-' \n ||" " substr('89ab',abs(random()) % 4 + 1, 1) \n ||" " substr(lower(hex(randomblob(2))),2) \n || '-' \n ||" " lower(hex(randomblob(6)))\n )\n )" ), nullable=False, ), sa.Column( "created", prefect.server.utilities.database.Timestamp(timezone=True), server_default=sa.text("(strftime('%Y-%m-%d %H:%M:%f000', 'now'))"), nullable=False, ), sa.Column( "updated", prefect.server.utilities.database.Timestamp(timezone=True), server_default=sa.text("(strftime('%Y-%m-%d %H:%M:%f000', 'now'))"), nullable=False, ), sa.Column("name", sa.String(), nullable=False), sa.Column( "state_type", sa.Enum( "SCHEDULED", "PENDING", "RUNNING", "COMPLETED", "FAILED", "CANCELLED", name="state_type", ), nullable=True, ), sa.Column("run_count", sa.Integer(), server_default="0", nullable=False), sa.Column( "expected_start_time", prefect.server.utilities.database.Timestamp(timezone=True), nullable=True, ), sa.Column( "next_scheduled_start_time", prefect.server.utilities.database.Timestamp(timezone=True), nullable=True, ), sa.Column( "start_time", prefect.server.utilities.database.Timestamp(timezone=True), nullable=True, ), sa.Column( "end_time", prefect.server.utilities.database.Timestamp(timezone=True), nullable=True, ), sa.Column("total_run_time", sa.Interval(), server_default="0", nullable=False), sa.Column("task_key", sa.String(), nullable=False), sa.Column("dynamic_key", sa.String(), nullable=False), sa.Column("cache_key", sa.String(), nullable=True), sa.Column( "cache_expiration", prefect.server.utilities.database.Timestamp(timezone=True), nullable=True, ), sa.Column("task_version", sa.String(), nullable=True), sa.Column( "empirical_policy", prefect.server.utilities.database.Pydantic( prefect.server.schemas.core.TaskRunPolicy ), server_default="{}", nullable=False, ), sa.Column( "task_inputs", prefect.server.utilities.database.Pydantic( Dict[ str, List[ Union[ prefect.server.schemas.core.TaskRunResult, prefect.server.schemas.core.Parameter, prefect.server.schemas.core.Constant, ] ], ] ), server_default="{}", nullable=False, ), sa.Column( "tags", prefect.server.utilities.database.JSON(astext_type=Text()), server_default="[]", nullable=False, ), sa.Column( "flow_run_id", prefect.server.utilities.database.UUID(), nullable=False ), sa.Column("state_id", prefect.server.utilities.database.UUID(), nullable=True), sa.ForeignKeyConstraint( ["flow_run_id"], ["flow_run.id"], name=op.f("fk_task_run__flow_run_id__flow_run"), ondelete="cascade", ), sa.ForeignKeyConstraint( ["state_id"], ["task_run_state.id"], name=op.f("fk_task_run__state_id__task_run_state"), ondelete="SET NULL", use_alter=True, ), sa.PrimaryKeyConstraint("id", name=op.f("pk_task_run")), ) op.create_index( "ix_task_run__end_time_desc", "task_run", [sa.text("end_time DESC")], unique=False, ) op.create_index( "ix_task_run__expected_start_time_desc", "task_run", [sa.text("expected_start_time DESC")], unique=False, ) op.create_index( op.f("ix_task_run__flow_run_id"), "task_run", ["flow_run_id"], unique=False ) op.create_index(op.f("ix_task_run__name"), "task_run", ["name"], unique=False) op.create_index( "ix_task_run__next_scheduled_start_time_asc", "task_run", [sa.text("next_scheduled_start_time ASC")], unique=False, ) op.create_index("ix_task_run__start_time", "task_run", ["start_time"], unique=False) op.create_index( op.f("ix_task_run__state_id"), "task_run", ["state_id"], unique=False ) op.create_index("ix_task_run__state_type", "task_run", ["state_type"], unique=False) op.create_index(op.f("ix_task_run__updated"), "task_run", ["updated"], unique=False) op.create_index( "uq_task_run__flow_run_id_task_key_dynamic_key", "task_run", ["flow_run_id", "task_key", "dynamic_key"], unique=True, ) op.create_table( "task_run_state", sa.Column( "id", prefect.server.utilities.database.UUID(), server_default=sa.text( "(\n (\n lower(hex(randomblob(4))) \n || '-' \n " " || lower(hex(randomblob(2))) \n || '-4' \n ||" " substr(lower(hex(randomblob(2))),2) \n || '-' \n ||" " substr('89ab',abs(random()) % 4 + 1, 1) \n ||" " substr(lower(hex(randomblob(2))),2) \n || '-' \n ||" " lower(hex(randomblob(6)))\n )\n )" ), nullable=False, ), sa.Column( "created", prefect.server.utilities.database.Timestamp(timezone=True), server_default=sa.text("(strftime('%Y-%m-%d %H:%M:%f000', 'now'))"), nullable=False, ), sa.Column( "updated", prefect.server.utilities.database.Timestamp(timezone=True), server_default=sa.text("(strftime('%Y-%m-%d %H:%M:%f000', 'now'))"), nullable=False, ), sa.Column( "type", sa.Enum( "SCHEDULED", "PENDING", "RUNNING", "COMPLETED", "FAILED", "CANCELLED", name="state_type", ), nullable=False, ), sa.Column( "timestamp", prefect.server.utilities.database.Timestamp(timezone=True), server_default=sa.text("(strftime('%Y-%m-%d %H:%M:%f000', 'now'))"), nullable=False, ), sa.Column("name", sa.String(), nullable=False), sa.Column("message", sa.String(), nullable=True), sa.Column( "state_details", prefect.server.utilities.database.Pydantic( prefect.server.schemas.states.StateDetails ), server_default="{}", nullable=False, ), sa.Column( "data", prefect.server.utilities.database.Pydantic(DataDocument), nullable=True, ), sa.Column( "task_run_id", prefect.server.utilities.database.UUID(), nullable=False ), sa.ForeignKeyConstraint( ["task_run_id"], ["task_run.id"], name=op.f("fk_task_run_state__task_run_id__task_run"), ondelete="cascade", ), sa.PrimaryKeyConstraint("id", name=op.f("pk_task_run_state")), ) op.create_index( op.f("ix_task_run_state__name"), "task_run_state", ["name"], unique=False ) op.create_index( op.f("ix_task_run_state__type"), "task_run_state", ["type"], unique=False ) op.create_index( op.f("ix_task_run_state__updated"), "task_run_state", ["updated"], unique=False ) op.create_index( "uq_task_run_state__task_run_id_timestamp_desc", "task_run_state", ["task_run_id", sa.text("timestamp DESC")], unique=True, ) def downgrade(): # Drop tables op.drop_index( "uq_task_run_state__task_run_id_timestamp_desc", table_name="task_run_state" ) op.drop_index(op.f("ix_task_run_state__updated"), table_name="task_run_state") op.drop_index(op.f("ix_task_run_state__type"), table_name="task_run_state") op.drop_index(op.f("ix_task_run_state__name"), table_name="task_run_state") op.drop_table("task_run_state") op.drop_index( "uq_task_run__flow_run_id_task_key_dynamic_key", table_name="task_run" ) op.drop_index(op.f("ix_task_run__updated"), table_name="task_run") op.drop_index("ix_task_run__state_type", table_name="task_run") op.drop_index(op.f("ix_task_run__state_id"), table_name="task_run") op.drop_index("ix_task_run__start_time", table_name="task_run") op.drop_index("ix_task_run__next_scheduled_start_time_asc", table_name="task_run") op.drop_index(op.f("ix_task_run__name"), table_name="task_run") op.drop_index(op.f("ix_task_run__flow_run_id"), table_name="task_run") op.drop_index("ix_task_run__expected_start_time_desc", table_name="task_run") op.drop_index("ix_task_run__end_time_desc", table_name="task_run") op.drop_table("task_run") op.drop_index( "uq_flow_run_state__flow_run_id_timestamp_desc", table_name="flow_run_state" ) op.drop_index(op.f("ix_flow_run_state__updated"), table_name="flow_run_state") op.drop_index(op.f("ix_flow_run_state__type"), table_name="flow_run_state") op.drop_index(op.f("ix_flow_run_state__name"), table_name="flow_run_state") op.drop_table("flow_run_state") op.drop_index("uq_flow_run__flow_id_idempotency_key", table_name="flow_run") op.drop_index(op.f("ix_flow_run__updated"), table_name="flow_run") op.drop_index("ix_flow_run__state_type", table_name="flow_run") op.drop_index(op.f("ix_flow_run__state_id"), table_name="flow_run") op.drop_index("ix_flow_run__start_time", table_name="flow_run") op.drop_index(op.f("ix_flow_run__parent_task_run_id"), table_name="flow_run") op.drop_index("ix_flow_run__next_scheduled_start_time_asc", table_name="flow_run") op.drop_index(op.f("ix_flow_run__name"), table_name="flow_run") op.drop_index(op.f("ix_flow_run__flow_version"), table_name="flow_run") op.drop_index(op.f("ix_flow_run__flow_id"), table_name="flow_run") op.drop_index("ix_flow_run__expected_start_time_desc", table_name="flow_run") op.drop_index("ix_flow_run__end_time_desc", table_name="flow_run") op.drop_index(op.f("ix_flow_run__deployment_id"), table_name="flow_run") op.drop_table("flow_run") op.drop_index("uq_deployment__flow_id_name", table_name="deployment") op.drop_index(op.f("ix_deployment__updated"), table_name="deployment") op.drop_index(op.f("ix_deployment__flow_id"), table_name="deployment") op.drop_table("deployment") op.drop_index( op.f("ix_task_run_state_cache__updated"), table_name="task_run_state_cache" ) op.drop_index( "ix_task_run_state_cache__cache_key_created_desc", table_name="task_run_state_cache", ) op.drop_table("task_run_state_cache") op.drop_index(op.f("ix_saved_search__updated"), table_name="saved_search") op.drop_table("saved_search") op.drop_index(op.f("ix_concurrency_limit__updated"), table_name="concurrency_limit") op.drop_index(op.f("ix_concurrency_limit__tag"), table_name="concurrency_limit") op.drop_table("concurrency_limit") op.drop_index(op.f("ix_log__updated"), table_name="log") op.drop_index(op.f("ix_log__timestamp"), table_name="log") op.drop_index(op.f("ix_log__task_run_id"), table_name="log") op.drop_index(op.f("ix_log__level"), table_name="log") op.drop_index(op.f("ix_log__flow_run_id"), table_name="log") op.drop_table("log") op.drop_index(op.f("ix_flow__updated"), table_name="flow") op.drop_table("flow")
DataDocument
python
joke2k__faker
tests/providers/test_misc.py
{ "start": 1406, "end": 27824 }
class ____: """Test miscellaneous provider methods""" num_samples = 10 def test_uuid4_str(self, faker, num_samples): pattern: Pattern = re.compile(r"[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}") for _ in range(num_samples): assert pattern.fullmatch(faker.uuid4()) def test_uuid4_int(self, faker, num_samples): for _ in range(num_samples): assert isinstance(faker.uuid4(cast_to=int), int) def test_uuid4_uuid_object(self, faker, num_samples): for _ in range(num_samples): uuid4 = faker.uuid4(cast_to=None) assert isinstance(uuid4, uuid.UUID) assert uuid4.version == 4 def test_uuid4_seedability(self, faker, num_samples): for _ in range(num_samples): random_seed = faker.random_int() faker.seed_instance(random_seed) expected_uuids = [faker.uuid4() for _ in range(100)] faker.seed_instance(random_seed) new_uuids = [faker.uuid4() for _ in range(100)] assert new_uuids == expected_uuids def test_zip_invalid_file(self, faker): with pytest.raises(ValueError): faker.zip(num_files="1") with pytest.raises(ValueError): faker.zip(num_files=0) with pytest.raises(ValueError): faker.zip(min_file_size="1") with pytest.raises(ValueError): faker.zip(min_file_size=0) with pytest.raises(ValueError): faker.zip(uncompressed_size="1") with pytest.raises(ValueError): faker.zip(uncompressed_size=0) def test_zip_one_byte_undersized(self, faker, num_samples): for _ in range(num_samples): num_files = faker.random.randint(1, 100) min_file_size = faker.random.randint(1, 1024) uncompressed_size = num_files * min_file_size - 1 # Will always fail because of bad size requirements with pytest.raises(AssertionError): faker.zip( uncompressed_size=uncompressed_size, num_files=num_files, min_file_size=min_file_size, ) def test_zip_exact_minimum_size(self, faker, num_samples): for _ in range(num_samples): num_files = faker.random.randint(1, 100) min_file_size = faker.random.randint(1, 1024) uncompressed_size = num_files * min_file_size zip_bytes = faker.zip( uncompressed_size=uncompressed_size, num_files=num_files, min_file_size=min_file_size, ) zip_buffer = io.BytesIO(zip_bytes) with zipfile.ZipFile(zip_buffer, "r") as zip_handle: # Verify zip archive is good assert zip_handle.testzip() is None # Verify zip archive has the correct number of files infolist = zip_handle.infolist() assert len(infolist) == num_files # Every file's size will be the minimum specified total_size = 0 for info in infolist: assert info.file_size == min_file_size total_size += info.file_size # The file sizes should sum up to the specified uncompressed size assert total_size == uncompressed_size def test_zip_over_minimum_size(self, faker, num_samples): for _ in range(num_samples): num_files = faker.random.randint(1, 100) min_file_size = faker.random.randint(1, 1024) expected_extra_bytes = faker.random.randint(1, 1024 * 1024) uncompressed_size = num_files * min_file_size + expected_extra_bytes zip_bytes = faker.zip( uncompressed_size=uncompressed_size, num_files=num_files, min_file_size=min_file_size, ) zip_buffer = io.BytesIO(zip_bytes) with zipfile.ZipFile(zip_buffer, "r") as zip_handle: # Verify zip archive is good assert zip_handle.testzip() is None # Verify zip archive has the correct number of files infolist = zip_handle.infolist() assert len(infolist) == num_files # Every file's size will be at least the minimum specified extra_bytes = 0 total_size = 0 for info in infolist: assert info.file_size >= min_file_size total_size += info.file_size if info.file_size > min_file_size: extra_bytes += info.file_size - min_file_size # The file sizes should sum up to the specified uncompressed size # and the extra bytes counted must be equal to the one expected assert total_size == uncompressed_size assert extra_bytes == expected_extra_bytes def test_zip_compression_py3(self, faker): num_files = 10 min_file_size = 512 uncompressed_size = 50 * 1024 compression_mapping = [ ("deflate", zipfile.ZIP_DEFLATED), ("gzip", zipfile.ZIP_DEFLATED), ("gz", zipfile.ZIP_DEFLATED), ("bzip2", zipfile.ZIP_BZIP2), ("bz2", zipfile.ZIP_BZIP2), ("lzma", zipfile.ZIP_LZMA), ("xz", zipfile.ZIP_LZMA), (None, zipfile.ZIP_STORED), ] for compression, compress_type in compression_mapping: zip_bytes = faker.zip( uncompressed_size=uncompressed_size, num_files=num_files, min_file_size=min_file_size, compression=compression, ) zip_buffer = io.BytesIO(zip_bytes) with zipfile.ZipFile(zip_buffer, "r") as zip_handle: # Verify zip archive is good assert zip_handle.testzip() is None # Verify compression type used for info in zip_handle.infolist(): assert info.compress_type == compress_type def test_tar_invalid_file(self, faker): with pytest.raises(ValueError): faker.tar(num_files="1") with pytest.raises(ValueError): faker.tar(num_files=0) with pytest.raises(ValueError): faker.tar(min_file_size="1") with pytest.raises(ValueError): faker.tar(min_file_size=0) with pytest.raises(ValueError): faker.tar(uncompressed_size="1") with pytest.raises(ValueError): faker.tar(uncompressed_size=0) def test_tar_one_byte_undersized(self, faker, num_samples): for _ in range(num_samples): num_files = faker.random.randint(1, 100) min_file_size = faker.random.randint(1, 1024) uncompressed_size = num_files * min_file_size - 1 # Will always fail because of conflicting size requirements with pytest.raises(AssertionError): faker.tar( uncompressed_size=uncompressed_size, num_files=num_files, min_file_size=min_file_size, ) def test_tar_exact_minimum_size(self, faker, num_samples): for _ in range(num_samples): num_files = faker.random.randint(1, 100) min_file_size = faker.random.randint(1, 1024) uncompressed_size = num_files * min_file_size tar_bytes = faker.tar( uncompressed_size=uncompressed_size, num_files=num_files, min_file_size=min_file_size, ) tar_buffer = io.BytesIO(tar_bytes) with tarfile.open(fileobj=tar_buffer) as tar_handle: # Verify tar has the correct number of files members = tar_handle.getmembers() assert len(members) == num_files # Every file's size will be the minimum specified total_size = 0 for member in members: assert member.size == min_file_size total_size += member.size # The file sizes should sum up to the specified uncompressed size assert total_size == uncompressed_size def test_tar_over_minimum_size(self, faker, num_samples): for _ in range(num_samples): num_files = faker.random.randint(1, 100) min_file_size = faker.random.randint(1, 1024) expected_extra_bytes = faker.random.randint(1, 1024 * 1024) uncompressed_size = num_files * min_file_size + expected_extra_bytes tar_bytes = faker.tar( uncompressed_size=uncompressed_size, num_files=num_files, min_file_size=min_file_size, ) tar_buffer = io.BytesIO(tar_bytes) with tarfile.open(fileobj=tar_buffer) as tar_handle: # Verify tar has the correct number of files members = tar_handle.getmembers() assert len(members) == num_files # Every file's size will be at least the minimum specified extra_bytes = 0 total_size = 0 for member in members: assert member.size >= min_file_size total_size += member.size if member.size > min_file_size: extra_bytes += member.size - min_file_size # The file sizes should sum up to the specified uncompressed size # and the extra bytes counted should be the one we expect assert total_size == uncompressed_size assert extra_bytes == expected_extra_bytes def test_tar_compression_py3(self, faker): num_files = 25 min_file_size = 512 uncompressed_size = 50 * 1024 compression_mapping = [ ("gzip", "r:gz"), ("gz", "r:gz"), ("bzip2", "r:bz2"), ("bz2", "r:bz2"), ("lzma", "r:xz"), ("xz", "r:xz"), (None, "r"), ] for compression, read_mode in compression_mapping: tar_bytes = faker.tar( uncompressed_size=uncompressed_size, num_files=num_files, min_file_size=min_file_size, compression=compression, ) tar_buffer = io.BytesIO(tar_bytes) with tarfile.open(fileobj=tar_buffer, mode=read_mode) as tar_handle: # Verify tar has the correct number of files members = tar_handle.getmembers() assert len(members) == num_files @unittest.skipUnless(PIL, "requires the Python Image Library") def test_image(self, faker): img = PIL.Image.open(io.BytesIO(faker.image())) assert img.size == (256, 256) assert img.format == "PNG" img = PIL.Image.open(io.BytesIO(faker.image(size=(2, 2), image_format="tiff"))) assert img.size == (2, 2) assert img.format == "TIFF" def test_image_no_pillow(self, faker): with patch.dict("sys.modules", {"PIL": None}): with pytest.raises(exceptions.UnsupportedFeature) as excinfo: faker.image() assert excinfo.value.name == "image" def test_dsv_with_invalid_values(self, faker): with pytest.raises(ValueError): faker.dsv(num_rows="1") with pytest.raises(ValueError): faker.dsv(num_rows=0) with pytest.raises(TypeError): faker.dsv(header=None, data_columns=1) with pytest.raises(TypeError): faker.dsv(header=1, data_columns=["???"]) with pytest.raises(ValueError): faker.dsv(header=["Column 1", "Column 2"], data_columns=["???"]) def test_dsv_no_header(self, faker, num_samples): data_columns = ["????", "?????"] for _ in range(num_samples): num_rows = faker.random.randint(1, 1000) dsv = faker.dsv(header=None, data_columns=data_columns, num_rows=num_rows) reader = csv.reader(io.StringIO(dsv), dialect="faker-csv") # Verify each row has correct number of columns for row in reader: assert len(row) == len(data_columns) # Verify correct number of lines read assert reader.line_num == num_rows def test_dsv_with_valid_header(self, faker, num_samples): header = ["Column 1", "Column 2"] data_columns = ["????", "?????"] for _ in range(num_samples): num_rows = faker.random.randint(1, 1000) dsv = faker.dsv(header=header, data_columns=data_columns, num_rows=num_rows) reader = csv.reader(io.StringIO(dsv), dialect="faker-csv") # Verify each row has correct number of columns for row in reader: assert len(row) == len(data_columns) # Verify correct number of lines read (additional header row) assert reader.line_num == num_rows + 1 def test_dsv_with_row_ids(self, faker, num_samples): data_columns = ["????", "?????"] for _ in range(num_samples): counter = 0 num_rows = faker.random.randint(1, 1000) dsv = faker.dsv( header=None, data_columns=data_columns, num_rows=num_rows, include_row_ids=True, ) reader = csv.reader(io.StringIO(dsv), dialect="faker-csv") # Verify each row has correct number of columns # and row ids increment correctly for row in reader: assert len(row) == len(data_columns) + 1 counter += 1 assert row[0] == str(counter) # Verify correct number of lines read assert reader.line_num == num_rows def test_dsv_data_columns(self, faker): num_rows = 10 data_columns = ["{{name}}", "#??-####", "{{address}}", "{{phone_number}}"] with patch.object(faker["en_US"].factories[0], "pystr_format") as mock_pystr_format: mock_pystr_format.assert_not_called() faker.dsv(data_columns=data_columns, num_rows=num_rows) # pystr_format will be called for each data column and each row calls = mock_pystr_format.call_args_list assert len(calls) == num_rows * len(data_columns) # Elements in data_columns will be used in sequence per row generation cycle column_cycle = itertools.cycle(data_columns) for args, kwargs in calls: assert args[0] == next(column_cycle) assert kwargs == {} def test_dsv_csvwriter_kwargs(self, faker): data_keys = ["header", "data_columns", "num_rows", "include_row_ids"] test_kwargs = { "dialect": "excel", "header": ["Column 1", "Column 2"], "data_columns": ["????", "?????"], "num_rows": 5, "include_row_ids": True, "delimiter": ";", "invalid_kwarg": "invalid_value", } with patch("faker.providers.misc.csv.writer") as mock_writer: mock_writer.assert_not_called() faker.dsv(**test_kwargs) assert mock_writer.call_count == 1 # Remove all data generation kwargs for key in data_keys: del test_kwargs[key] # Verify csv.writer was called with the remaining kwargs for args, kwargs in mock_writer.call_args_list: assert kwargs == test_kwargs @unittest.skipUnless(xmltodict, "requires the Python xmltodict Library") def test_xml(self, faker): try: xml.etree.ElementTree.fromstring(faker.xml()) except xml.etree.ElementTree.ParseError: raise AssertionError("The XML format is invalid.") def test_xml_no_xmltodict(self, faker): with patch.dict("sys.modules", {"xmltodict": None}): with pytest.raises(exceptions.UnsupportedFeature) as excinfo: faker.xml() assert excinfo.value.name == "xml" def test_csv_helper_method(self, faker): kwargs = { "header": ["Column 1", "Column 2"], "data_columns": ["????", "?????"], "num_rows": 5, "include_row_ids": True, } with patch("faker.providers.misc.Provider.dsv") as mock_dsv: mock_dsv.assert_not_called() faker.csv(**kwargs) kwargs["delimiter"] = "," mock_dsv.assert_called_once_with(**kwargs) def test_tsv_helper_method(self, faker): kwargs = { "header": ["Column 1", "Column 2"], "data_columns": ["????", "?????"], "num_rows": 5, "include_row_ids": True, } with patch("faker.providers.misc.Provider.dsv") as mock_dsv: mock_dsv.assert_not_called() faker.tsv(**kwargs) kwargs["delimiter"] = "\t" mock_dsv.assert_called_once_with(**kwargs) def test_psv_helper_method(self, faker): kwargs = { "header": ["Column 1", "Column 2"], "data_columns": ["????", "?????"], "num_rows": 5, "include_row_ids": True, } with patch("faker.providers.misc.Provider.dsv") as mock_dsv: mock_dsv.assert_not_called() faker.psv(**kwargs) kwargs["delimiter"] = "|" mock_dsv.assert_called_once_with(**kwargs) def test_json_with_arguments(self, faker_with_foobar): kwargs = { "data_columns": [ ("item1", "{{ foo_bar:argument_group }}"), ("item2", "foo_bar", {"param": "BAZ"}), ], "num_rows": 1, } json_data = json.loads(faker_with_foobar.json(**kwargs)) assert json_data.get("item1") == "FooBarBaz" assert json_data.get("item2") == "FooBarBAZ" def test_json_multiple_rows(self, faker_with_foobar): kwargs = { "data_columns": {"item": "foo_bar"}, "num_rows": 2, } json_data = json.loads(faker_with_foobar.json(**kwargs)) assert isinstance(json_data, list) and len(json_data) == 2 def test_json_passthrough_values(self, faker_with_foobar): kwargs = { "data_columns": { "item1": 1, "item2": 1.0, "item3": True, "item4": "@fixed", }, "num_rows": 1, } json_data = json.loads(faker_with_foobar.json(**kwargs)) assert json_data["item1"] == 1 assert json_data["item2"] == 1.0 assert json_data["item3"] is True assert json_data["item4"] == "fixed" def test_json_type_integrity_int(self, faker_with_foobar): kwargs = { "data_columns": { "item1": "test_integer", "item2": "test_integer:double", }, "num_rows": 1, } json_data = json.loads(faker_with_foobar.json(**kwargs)) assert isinstance(json_data["item1"], int) assert json_data["item2"] == 2 def test_json_type_integrity_float(self, faker_with_foobar): kwargs = { "data_columns": { "item1": "test_float", "item2": "test_float:double", }, "num_rows": 1, } json_data = json.loads(faker_with_foobar.json(**kwargs)) assert isinstance(json_data["item1"], float) assert json_data["item2"] == 2.2 def test_json_invalid_data_columns(self, faker_with_foobar): kwargs = { "data_columns": (("item", "foo_bar"),), "num_rows": 1, } with pytest.raises(TypeError) as excinfo: json.loads(faker_with_foobar.json(**kwargs)) assert str(excinfo.value) == "Invalid data_columns type. Must be a dictionary or list" def test_json_list_format_invalid_arguments_type(self, faker_with_foobar): kwargs = { "data_columns": [("item", "foo_bar", ["wrong"])], "num_rows": 1, } with pytest.raises(TypeError) as excinfo: faker_with_foobar.json(**kwargs) assert str(excinfo.value) == "Invalid arguments type. Must be a dictionary" def test_json_list_format_nested_list_of_values(self, faker_with_foobar): kwargs = { "data_columns": [ ( "list", [ (None, "{{ foo_bar }}s"), (None, "foo_bar"), ], ), ], "num_rows": 1, } json_data = json.loads(faker_with_foobar.json(**kwargs)) assert json_data["list"][0] == "FooBars" assert json_data["list"][1] == "FooBar" def test_json_list_format_nested_list_of_objects(self, faker_with_foobar): kwargs = { "data_columns": [ ( "list", [ ("item", "{{ foo_bar }}s"), ("item", "foo_bar"), ], ), ], "num_rows": 1, } json_data = json.loads(faker_with_foobar.json(**kwargs)) assert json_data["list"][0]["item"] == "FooBars" assert json_data["list"][1]["item"] == "FooBar" def test_json_list_format_nested_objects(self, faker_with_foobar): kwargs = { "data_columns": [ ( "dict", ( ("item1", "{{ foo_bar }}s"), ("item2", "foo_bar"), ), ), ], "num_rows": 1, } json_data = json.loads(faker_with_foobar.json(**kwargs)) assert json_data["dict"]["item1"] == "FooBars" assert json_data["dict"]["item2"] == "FooBar" def test_json_dict_format_nested_list_of_values(self, faker_with_foobar): kwargs = { "data_columns": { "list": [ "{{ foo_bar }}s", "foo_bar", ], }, "num_rows": 1, } json_data = json.loads(faker_with_foobar.json(**kwargs)) assert json_data["list"][0] == "FooBars" assert json_data["list"][1] == "FooBar" def test_json_dict_format_nested_list_of_objects(self, faker_with_foobar): kwargs = { "data_columns": { "list": [ {"item": "{{ foo_bar }}s"}, {"item": "foo_bar"}, ], }, "num_rows": 1, } json_data = json.loads(faker_with_foobar.json(**kwargs)) assert json_data["list"][0]["item"] == "FooBars" assert json_data["list"][1]["item"] == "FooBar" def test_json_dict_format_nested_objects(self, faker_with_foobar): kwargs = { "data_columns": { "dict": { "item1": "{{ foo_bar }}s", "item2": "foo_bar", }, }, "num_rows": 1, } json_data = json.loads(faker_with_foobar.json(**kwargs)) assert json_data["dict"]["item1"] == "FooBars" assert json_data["dict"]["item2"] == "FooBar" def test_json_type_integrity_datetime_using_encoder(self, faker_with_foobar): class DateTimeEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, datetime.datetime): return str(obj) # Let the base class default method raise the TypeError return json.JSONEncoder.default(self, obj) kwargs = { "data_columns": {"item1": "test_date_time"}, "num_rows": 1, "cls": DateTimeEncoder, } json_data = json.loads(faker_with_foobar.json(**kwargs)) assert isinstance(json_data["item1"], str) assert json_data["item1"] == "2022-12-22 13:42:33.000123" def test_json_type_integrity_datetime_no_encoder(self, faker_with_foobar): kwargs = {"data_columns": {"item1": "test_date_time"}, "num_rows": 1} with pytest.raises(TypeError): faker_with_foobar.json(**kwargs) def test_json_bytes(self, faker_with_foobar): kwargs = {"data_columns": {"item1": "foo_bar"}, "num_rows": 1} json_data_bytes = faker_with_foobar.json_bytes(**kwargs) assert isinstance(json_data_bytes, bytes) json_data = json.loads(json_data_bytes.decode()) assert json_data["item1"] == "FooBar" def test_fixed_width_with_arguments(self, faker_with_foobar): kwargs = { "data_columns": [ (9, "{{ foo_bar:argument_group }}"), (9, "foo_bar", {"param": "BAR"}), ], "num_rows": 2, } fixed_width_string = faker_with_foobar.fixed_width(**kwargs) for row in fixed_width_string.split("\n"): assert len(row) == 18 assert row[0:9].strip() == "FooBarBaz" assert row[9:18].strip() == "FooBarBAR" def test_fixed_width_invalid_arguments_type(self, faker_with_foobar): kwargs = { "data_columns": [(9, "foo_bar", ["wrong"])], "num_rows": 1, } with pytest.raises(TypeError) as excinfo: faker_with_foobar.fixed_width(**kwargs) assert str(excinfo.value) == "Invalid arguments type. Must be a dictionary" def test_md5(self, faker): assert isinstance(faker.md5(), str) assert isinstance(faker.md5(raw_output=True), bytes) def test_sha1(self, faker): assert isinstance(faker.sha1(), str) assert isinstance(faker.sha1(raw_output=True), bytes) def test_sha256(self, faker): assert isinstance(faker.sha256(), str) assert isinstance(faker.sha256(raw_output=True), bytes)
TestMiscProvider
python
pytorch__pytorch
test/test_testing.py
{ "start": 51666, "end": 54146 }
class ____(TestCase): def test_matching(self): ccol_indices = (0, 1, 2) row_indices = (1, 0) values = ([[1]], [[2]]) actual = torch.sparse_bsc_tensor(ccol_indices, row_indices, values, size=(2, 2)) expected = actual.clone() for fn in assert_close_with_inputs(actual, expected): fn() def test_mismatching_ccol_indices_msg(self): actual_ccol_indices = (0, 1, 2) actual_row_indices = (0, 1) actual_values = ([[1]], [[2]]) actual = torch.sparse_bsc_tensor(actual_ccol_indices, actual_row_indices, actual_values, size=(2, 2)) expected_ccol_indices = (0, 2, 2) expected_row_indices = actual_row_indices expected_values = actual_values expected = torch.sparse_bsc_tensor(expected_ccol_indices, expected_row_indices, expected_values, size=(2, 2)) for fn in assert_close_with_inputs(actual, expected): with self.assertRaisesRegex(AssertionError, re.escape("Sparse BSC ccol_indices")): fn() def test_mismatching_row_indices_msg(self): actual_ccol_indices = (0, 1, 2) actual_row_indices = (1, 0) actual_values = ([[1]], [[2]]) actual = torch.sparse_bsc_tensor(actual_ccol_indices, actual_row_indices, actual_values, size=(2, 2)) expected_ccol_indices = actual_ccol_indices expected_row_indices = (1, 1) expected_values = actual_values expected = torch.sparse_bsc_tensor(expected_ccol_indices, expected_row_indices, expected_values, size=(2, 2)) for fn in assert_close_with_inputs(actual, expected): with self.assertRaisesRegex(AssertionError, re.escape("Sparse BSC row_indices")): fn() def test_mismatching_values_msg(self): actual_ccol_indices = (0, 1, 2) actual_row_indices = (1, 0) actual_values = ([[1]], [[2]]) actual = torch.sparse_bsc_tensor(actual_ccol_indices, actual_row_indices, actual_values, size=(2, 2)) expected_ccol_indices = actual_ccol_indices expected_row_indices = actual_row_indices expected_values = ([[1]], [[3]]) expected = torch.sparse_bsc_tensor(expected_ccol_indices, expected_row_indices, expected_values, size=(2, 2)) for fn in assert_close_with_inputs(actual, expected): with self.assertRaisesRegex(AssertionError, re.escape("Sparse BSC values")): fn()
TestAssertCloseSparseBSC
python
pydata__xarray
xarray/namedarray/_typing.py
{ "start": 6359, "end": 6911 }
class ____( _arrayapi[_ShapeType_co, _DType_co], Protocol[_ShapeType_co, _DType_co] ): """ Chunked duck array supporting NEP 47. Corresponds to np.ndarray. """ @property def chunks(self) -> _Chunks: ... # NamedArray can most likely use both __array_function__ and __array_namespace__: _chunkedarrayfunction_or_api = (_chunkedarrayfunction, _chunkedarrayapi) chunkedduckarray = Union[ _chunkedarrayfunction[_ShapeType_co, _DType_co], _chunkedarrayapi[_ShapeType_co, _DType_co], ] @runtime_checkable
_chunkedarrayapi
python
pypa__setuptools
setuptools/command/editable_wheel.py
{ "start": 16138, "end": 17050 }
class ____: def __init__(self, dist: Distribution, name: str, path_entries: list[Path]) -> None: self.dist = dist self.name = name self.path_entries = path_entries def __call__( self, wheel: WheelFile, files: list[str], mapping: Mapping[str, str] ) -> None: entries = "\n".join(str(p.resolve()) for p in self.path_entries) contents = _encode_pth(f"{entries}\n") wheel.writestr(f"__editable__.{self.name}.pth", contents) def __enter__(self) -> Self: msg = f""" Editable install will be performed using .pth file to extend `sys.path` with: {list(map(os.fspath, self.path_entries))!r} """ _logger.warning(msg + _LENIENT_WARNING) return self def __exit__( self, _exc_type: object, _exc_value: object, _traceback: object, ) -> None: pass
_StaticPth
python
ray-project__ray
python/ray/llm/_internal/batch/processor/serve_deployment_proc.py
{ "start": 358, "end": 2921 }
class ____(ProcessorConfig): """The configuration for the serve deployment processor.""" # Configurations used to build the serve deployment deployment_name: str = Field( description="The name of the serve deployment to use.", ) app_name: str = Field( description="The name of the serve application to use.", default="default", ) dtype_mapping: Dict[str, Type[Any]] = Field( description="A dictionary mapping data type names to their corresponding request classes for the serve deployment.", default=None, ) def build_serve_deployment_processor( config: ServeDeploymentProcessorConfig, preprocess: Optional[UserDefinedFunction] = None, postprocess: Optional[UserDefinedFunction] = None, preprocess_map_kwargs: Optional[Dict[str, Any]] = None, postprocess_map_kwargs: Optional[Dict[str, Any]] = None, ) -> Processor: """Construct a processor that runs a serve deployment. Args: config: The configuration for the processor. preprocess: An optional lambda function that takes a row (dict) as input and returns a preprocessed row (dict). The output row must contain the required fields for the following processing stages. postprocess: An optional lambda function that takes a row (dict) as input and returns a postprocessed row (dict). preprocess_map_kwargs: Optional kwargs to pass to Dataset.map() for the preprocess stage (e.g., num_cpus, memory, concurrency). postprocess_map_kwargs: Optional kwargs to pass to Dataset.map() for the postprocess stage (e.g., num_cpus, memory, concurrency). Returns: The constructed processor. """ stages = [ ServeDeploymentStage( fn_constructor_kwargs=dict( deployment_name=config.deployment_name, app_name=config.app_name, dtype_mapping=config.dtype_mapping, ), map_batches_kwargs=dict( concurrency=config.concurrency, ), ) ] # TODO (Kourosh): Add telemetry for ServeDeploymentStage processor = Processor( config, stages, preprocess=preprocess, postprocess=postprocess, preprocess_map_kwargs=preprocess_map_kwargs, postprocess_map_kwargs=postprocess_map_kwargs, ) return processor ProcessorBuilder.register( ServeDeploymentProcessorConfig, build_serve_deployment_processor )
ServeDeploymentProcessorConfig
python
matplotlib__matplotlib
lib/mpl_toolkits/axes_grid1/parasite_axes.py
{ "start": 183, "end": 2984 }
class ____: def __init__(self, parent_axes, aux_transform=None, *, viewlim_mode=None, **kwargs): self._parent_axes = parent_axes self.transAux = aux_transform self.set_viewlim_mode(viewlim_mode) kwargs["frameon"] = False super().__init__(parent_axes.get_figure(root=False), parent_axes._position, **kwargs) def clear(self): super().clear() martist.setp(self.get_children(), visible=False) self._get_lines = self._parent_axes._get_lines self._parent_axes.callbacks._connect_picklable( "xlim_changed", self._sync_lims) self._parent_axes.callbacks._connect_picklable( "ylim_changed", self._sync_lims) def get_axes_locator(self): return self._parent_axes.get_axes_locator() def pick(self, mouseevent): # This most likely goes to Artist.pick (depending on axes_class given # to the factory), which only handles pick events registered on the # axes associated with each child: super().pick(mouseevent) # But parasite axes are additionally given pick events from their host # axes (cf. HostAxesBase.pick), which we handle here: for a in self.get_children(): if (hasattr(mouseevent.inaxes, "parasites") and self in mouseevent.inaxes.parasites): a.pick(mouseevent) # aux_transform support def _set_lim_and_transforms(self): if self.transAux is not None: self.transAxes = self._parent_axes.transAxes self.transData = self.transAux + self._parent_axes.transData self._xaxis_transform = mtransforms.blended_transform_factory( self.transData, self.transAxes) self._yaxis_transform = mtransforms.blended_transform_factory( self.transAxes, self.transData) else: super()._set_lim_and_transforms() def set_viewlim_mode(self, mode): _api.check_in_list([None, "equal", "transform"], mode=mode) self._viewlim_mode = mode def get_viewlim_mode(self): return self._viewlim_mode def _sync_lims(self, parent): viewlim = parent.viewLim.frozen() mode = self.get_viewlim_mode() if mode is None: pass elif mode == "equal": self.viewLim.set(viewlim) elif mode == "transform": self.viewLim.set(viewlim.transformed(self.transAux.inverted())) else: _api.check_in_list([None, "equal", "transform"], mode=mode) # end of aux_transform support parasite_axes_class_factory = cbook._make_class_factory( ParasiteAxesBase, "{}Parasite") ParasiteAxes = parasite_axes_class_factory(Axes)
ParasiteAxesBase
python
facelessuser__pymdown-extensions
tests/test_extensions/test_superfences.py
{ "start": 12474, "end": 14021 }
class ____(util.MdCase): """Test highlight line wraps.""" extension = ['pymdownx.highlight', 'pymdownx.superfences'] extension_configs = { 'pymdownx.highlight': { 'anchor_linenums': True, 'linenums_style': 'pymdownx-inline' } } def test_linespans(self): """Test wrapping a line in line spans.""" self.check_markdown( r''' ```python linenums="2" import test ``` ''', r''' <div class="highlight"><pre><span></span><code><a id="__codelineno-0-2" name="__codelineno-0-2"></a><a href="#__codelineno-0-2"><span class="linenos" data-linenos="2 "></span></a><span class="kn">import</span><span class="w"> </span><span class="nn">test</span> </code></pre></div> ''', # noqa: E501 True ) def test_linespans_id(self): """Test wrapping a line in line spans.""" self.check_markdown( r''' ```{.python #id linenums="2"} import test ``` ''', r''' <div id="id" class="highlight"><pre><span></span><code><a id="__codelineno-id-2" name="__codelineno-id-2"></a><a href="#__codelineno-id-2"><span class="linenos" data-linenos="2 "></span></a><span class="kn">import</span><span class="w"> </span><span class="nn">test</span> </code></pre></div> ''', # noqa: E501 True )
TestHighlightAnchorLinenumsPymdownxInline