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
huggingface__transformers
examples/quantization/custom_quantization_int8_example.py
{ "start": 488, "end": 4137 }
class ____(torch.nn.Module): def __init__(self, in_features, out_features, bias, dtype=torch.float32): super().__init__() self.in_features = in_features self.out_features = out_features self.register_buffer("weight", torch.zeros((out_features, in_features), dtype=torch.int8)) self.register_buffer("weight_scale", torch.zeros((out_features, 1), dtype=dtype)) if bias: self.register_buffer("bias", torch.zeros((self.out_features), dtype=dtype)) else: self.bias = None def forward(self, x): dequant_weight = self.weight * self.weight_scale output = F.linear(x, dequant_weight) if self.bias is not None: output = output + self.bias return output # Function to replace standard linear layers with INT8 symmetric quantized layers def _replace_with_int8_symmetric_linear( model, modules_to_not_convert=None, current_key_name=None, quantization_config=None, has_been_replaced=False, pre_quantized=False, ): """ Recursively replaces nn.Linear modules with Int8SymmetricLinear modules. """ if current_key_name is None: current_key_name = [] for name, module in model.named_children(): current_key_name.append(name) if (isinstance(module, nn.Linear)) and name not in modules_to_not_convert: # Check if the current key is not in the `modules_to_not_convert` current_key_name_str = ".".join(current_key_name) if not any( (key + "." in current_key_name_str) or (key == current_key_name_str) for key in modules_to_not_convert ): with init_empty_weights(include_buffers=True): in_features = module.in_features out_features = module.out_features model._modules[name] = Int8SymmetricLinear( in_features, out_features, module.bias is not None, dtype=module.weight.dtype ) has_been_replaced = True model._modules[name].requires_grad_(False) if len(list(module.children())) > 0: _, has_been_replaced = _replace_with_int8_symmetric_linear( module, modules_to_not_convert, current_key_name, quantization_config, has_been_replaced=has_been_replaced, pre_quantized=pre_quantized, ) # Remove the last key for recursion current_key_name.pop(-1) return model, has_been_replaced def replace_with_int8_symmetric_linear( model, modules_to_not_convert=None, current_key_name=None, quantization_config=None, pre_quantized=False ): """ Main function to replace model layers with INT8 symmetric quantized versions. """ modules_to_not_convert = ["lm_head"] if modules_to_not_convert is None else modules_to_not_convert if quantization_config.modules_to_not_convert is not None: modules_to_not_convert.extend(quantization_config.modules_to_not_convert) modules_to_not_convert = list(set(modules_to_not_convert)) model, has_been_replaced = _replace_with_int8_symmetric_linear( model, modules_to_not_convert, current_key_name, quantization_config, pre_quantized=pre_quantized ) if not has_been_replaced: raise ValueError( "You are loading your model using INT8 symmetric quantization but no linear modules were found in your model." ) return model @register_quantization_config("int8_symmetric")
Int8SymmetricLinear
python
encode__django-rest-framework
tests/test_model_serializer.py
{ "start": 39264, "end": 39936 }
class ____(TestCase): def test_queryset_all(self): class TestSerializer(serializers.ModelSerializer): additional_attr = serializers.CharField() class Meta: model = OneFieldModel fields = ('char_field', 'additional_attr') OneFieldModel.objects.create(char_field='abc') qs = OneFieldModel.objects.all() for o in qs: o.additional_attr = '123' serializer = TestSerializer(instance=qs, many=True) expected = [{ 'char_field': 'abc', 'additional_attr': '123', }] assert serializer.data == expected
Issue2704TestCase
python
allegroai__clearml
clearml/automation/scheduler.py
{ "start": 3309, "end": 12801 }
class ____(BaseScheduleJob): _weekdays_ind = ( "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday", ) execution_limit_hours = attrib(type=float, default=None) recurring = attrib(type=bool, default=True) starting_time = attrib(type=datetime, converter=datetime_from_isoformat, default=None) minute = attrib(type=float, default=None) hour = attrib(type=float, default=None) day = attrib(default=None) weekdays = attrib(default=None) month = attrib(type=float, default=None) year = attrib(type=float, default=None) _next_run = attrib(type=datetime, converter=datetime_from_isoformat, default=None) _execution_timeout = attrib(type=datetime, converter=datetime_from_isoformat, default=None) _last_executed = attrib(type=datetime, converter=datetime_from_isoformat, default=None) _schedule_counter = attrib(type=int, default=0) def verify(self) -> None: def check_integer(value: Union[int, float, str, None]) -> bool: try: return False if not isinstance(value, (int, float)) or int(value) != float(value) else True except (TypeError, ValueError): return False super(ScheduleJob, self).verify() if self.weekdays and self.day not in (None, 0, 1): raise ValueError("`weekdays` and `day` combination is not valid (day must be None,0 or 1)") if self.weekdays and any(w not in self._weekdays_ind for w in self.weekdays): raise ValueError("`weekdays` must be a list of strings, valid values are: {}".format(self._weekdays_ind)) if not (self.minute or self.hour or self.day or self.month or self.year): raise ValueError("Schedule time/date was not provided") if self.minute and not check_integer(self.minute): raise ValueError("Schedule `minute` must be an integer") if self.hour and not check_integer(self.hour): raise ValueError("Schedule `hour` must be an integer") if self.day and not check_integer(self.day): raise ValueError("Schedule `day` must be an integer") if self.month and not check_integer(self.month): raise ValueError("Schedule `month` must be an integer") if self.year and not check_integer(self.year): raise ValueError("Schedule `year` must be an integer") def next_run(self) -> Optional[datetime]: return self._next_run def get_execution_timeout(self) -> Optional[datetime]: return self._execution_timeout def next(self) -> Optional[datetime]: """ :return: Return the next run datetime, None if no scheduling needed """ if not self.recurring and self._last_executed: self._next_run = None return self._next_run # make sure we have a starting time if not self.starting_time: self.starting_time = datetime.now(timezone.utc) # check if we have a specific date if self.year and self.year > 2000: # this is by definition a single execution only if self._last_executed: return None self._next_run = datetime( year=int(self.year), month=int(self.month or 1), day=int(self.day or 1), hour=int(self.hour or 0), minute=int(self.minute or 0), ) if self.weekdays: self._next_run += relativedelta(weekday=self.get_weekday_ord(self.weekdays[0])) return self._next_run # check if we have a specific day of the week weekday = None if self.weekdays: # get previous weekday _weekdays = [self.get_weekday_ord(w) for w in self.weekdays] try: prev_weekday_ind = _weekdays.index(self._last_executed.weekday()) if self._last_executed else -1 except ValueError: # in case previous execution was not in the weekday (for example executed immediately at scheduling) prev_weekday_ind = -1 weekday = _weekdays[(prev_weekday_ind + 1) % len(_weekdays)] prev_timestamp = self._last_executed or self.starting_time # fix first scheduled job should be as close as possible to starting time if self._schedule_counter < 1: # we should get here the first time we need to schedule a job, after that the delta is fixed # If we have execute_immediately we need to get here after the first execution # (so even through we have self._last_executed) # if this is a daily schedule and we can still run it today, then we should run0 = self._calc_next_run(self.starting_time, weekday) run1 = self._calc_next_run(run0, weekday) delta = run1 - run0 optional_first_timestamp = self._calc_next_run(prev_timestamp - delta, weekday) if optional_first_timestamp > prev_timestamp: # this is us, we can still run it self._next_run = optional_first_timestamp return self._next_run self._next_run = self._calc_next_run(prev_timestamp, weekday) return self._next_run def _calc_next_run(self, prev_timestamp: datetime, weekday: Optional[int]) -> datetime: # make sure that if we have a specific day we zero the minutes/hours/seconds if self.year: prev_timestamp = datetime( year=prev_timestamp.year, month=self.month or prev_timestamp.month, day=self.day or 1, ) elif self.month: prev_timestamp = datetime( year=prev_timestamp.year, month=prev_timestamp.month, day=self.day or 1, ) elif self.day is None and weekday is not None: # notice we assume every X hours on specific weekdays # other combinations (i.e. specific time at weekdays, is covered later) next_timestamp = datetime( year=prev_timestamp.year, month=prev_timestamp.month, day=prev_timestamp.day, hour=prev_timestamp.hour, minute=prev_timestamp.minute, ) next_timestamp += relativedelta( years=self.year or 0, months=0 if self.year else (self.month or 0), hours=self.hour or 0, minutes=self.minute or 0, weekday=weekday if not self._last_executed else None, ) # start a new day if next_timestamp.day != prev_timestamp.day: next_timestamp = datetime( year=prev_timestamp.year, month=prev_timestamp.month, day=prev_timestamp.day, ) + relativedelta( years=self.year or 0, months=0 if self.year else (self.month or 0), hours=self.hour or 0, minutes=self.minute or 0, weekday=weekday, ) return next_timestamp elif self.day is not None and weekday is not None: # push to the next day (so we only have once a day) prev_timestamp = datetime( year=prev_timestamp.year, month=prev_timestamp.month, day=prev_timestamp.day, ) + relativedelta(days=1) elif self.day: # reset minutes in the hour (we will be adding additional hour/minute anyhow) prev_timestamp = datetime( year=prev_timestamp.year, month=prev_timestamp.month, day=prev_timestamp.day, ) elif self.hour: # reset minutes in the hour (we will be adding additional minutes anyhow) prev_timestamp = datetime( year=prev_timestamp.year, month=prev_timestamp.month, day=prev_timestamp.day, hour=prev_timestamp.hour, ) return prev_timestamp + relativedelta( years=self.year or 0, months=0 if self.year else (self.month or 0), days=0 if self.month or self.year else ((self.day or 0) if weekday is None else 0), hours=self.hour or 0, minutes=self.minute or 0, weekday=weekday, ) def run(self, task_id: Optional[str]) -> datetime: super(ScheduleJob, self).run(task_id) if self._last_executed or self.starting_time != datetime.fromtimestamp(0): self._schedule_counter += 1 self._last_executed = datetime.now(timezone.utc) if self.execution_limit_hours and task_id: self._execution_timeout = self._last_executed + relativedelta( hours=int(self.execution_limit_hours), minutes=int((self.execution_limit_hours - int(self.execution_limit_hours)) * 60), ) else: self._execution_timeout = None return self._last_executed @classmethod def get_weekday_ord(cls, weekday: Union[int, str]) -> int: if isinstance(weekday, int): return min(6, max(weekday, 0)) return cls._weekdays_ind.index(weekday) @attrs
ScheduleJob
python
nedbat__coveragepy
coverage/results.py
{ "start": 6560, "end": 10386 }
class ____: """ For reducing an `Analysis` to a subset of its lines. Originally this was a simpler method on Analysis, but that led to quadratic behavior. This class does the bulk of the work up-front to provide the same results in linear time. Create an AnalysisNarrower from an Analysis, bulk-add region lines to it with `add_regions`, then individually request new narrowed Analysis objects for each region with `narrow`. Doing most of the work in limited calls to `add_regions` lets us avoid poor performance. """ # In this class, regions are represented by a frozenset of their lines. def __init__(self, analysis: Analysis) -> None: self.analysis = analysis self.region2arc_possibilities: dict[TRegionLines, set[TArc]] = collections.defaultdict(set) self.region2arc_executed: dict[TRegionLines, set[TArc]] = collections.defaultdict(set) self.region2exit_counts: dict[TRegionLines, dict[TLineNo, int]] = collections.defaultdict( dict ) def add_regions(self, liness: Iterable[set[TLineNo]]) -> None: """ Pre-process a number of sets of line numbers. Later calls to `narrow` with one of these sets will provide a narrowed Analysis. """ if self.analysis.has_arcs: line2region: dict[TLineNo, TRegionLines] = {} for lines in liness: fzlines = frozenset(lines) for line in lines: line2region[line] = fzlines def collect_arcs( arc_set: set[TArc], region2arcs: dict[TRegionLines, set[TArc]], ) -> None: for a, b in arc_set: if r := line2region.get(a): region2arcs[r].add((a, b)) if r := line2region.get(b): region2arcs[r].add((a, b)) collect_arcs(self.analysis.arc_possibilities_set, self.region2arc_possibilities) collect_arcs(self.analysis.arcs_executed_set, self.region2arc_executed) for lno, num in self.analysis.exit_counts.items(): if r := line2region.get(lno): self.region2exit_counts[r][lno] = num def narrow(self, lines: set[TLineNo]) -> Analysis: """Create a narrowed Analysis. The current analysis is copied to make a new one that only considers the lines in `lines`. """ # Technically, the set intersections in this method are still O(N**2) # since this method is called N times, but they're very fast and moving # them to `add_regions` won't avoid the quadratic time. statements = self.analysis.statements & lines excluded = self.analysis.excluded & lines executed = self.analysis.executed & lines if self.analysis.has_arcs: fzlines = frozenset(lines) arc_possibilities_set = self.region2arc_possibilities[fzlines] arcs_executed_set = self.region2arc_executed[fzlines] exit_counts = self.region2exit_counts[fzlines] no_branch = self.analysis.no_branch & lines else: arc_possibilities_set = set() arcs_executed_set = set() exit_counts = {} no_branch = set() return Analysis( precision=self.analysis.precision, filename=self.analysis.filename, has_arcs=self.analysis.has_arcs, statements=statements, excluded=excluded, executed=executed, arc_possibilities_set=arc_possibilities_set, arcs_executed_set=arcs_executed_set, exit_counts=exit_counts, no_branch=no_branch, ) @dataclasses.dataclass
AnalysisNarrower
python
mlflow__mlflow
mlflow/telemetry/events.py
{ "start": 168, "end": 382 }
class ____: name: str @classmethod def parse(cls, arguments: dict[str, Any]) -> dict[str, Any] | None: """ Parse the arguments and return the params. """ return None
Event
python
facebook__pyre-check
tools/generate_taint_models/tests/get_models_filtered_by_callable_test.py
{ "start": 1195, "end": 1532 }
class ____(unittest.TestCase): def test_compute_models(self) -> None: generator = ModelsFilteredByCallableGenerator( generator_to_filter=TestModelGenerator(), filter=is_even_index ) self.assertListEqual(generator.compute_models([]), [TestModel(0), TestModel(2)])
ModelsFilteredByCallableGeneratorTest
python
google__pytype
pytype/pytd/serialize_ast.py
{ "start": 526, "end": 770 }
class ____(visitors.Visitor): """Visitor to find class and function types.""" def __init__(self): super().__init__() self.class_type_nodes = [] def EnterClassType(self, n): self.class_type_nodes.append(n)
FindClassTypesVisitor
python
numba__numba
numba/core/types/scalars.py
{ "start": 3505, "end": 4084 }
class ____(Number): def __init__(self, name, underlying_float, **kwargs): super(Complex, self).__init__(name, **kwargs) self.underlying_float = underlying_float # Determine bitwidth assert self.name.startswith('complex') bitwidth = int(self.name[7:]) self.bitwidth = bitwidth def cast_python_value(self, value): return getattr(np, self.name)(value) def __lt__(self, other): if self.__class__ is not other.__class__: return NotImplemented return self.bitwidth < other.bitwidth
Complex
python
weaviate__weaviate-python-client
weaviate/collections/config/executor.py
{ "start": 1473, "end": 23218 }
class ____(Generic[ConnectionType]): def __init__( self, connection: ConnectionType, name: str, tenant: Optional[str] = None, ) -> None: self._connection = connection self._name = name self._tenant = tenant def __get(self) -> executor.Result[Dict[str, Any]]: def resp(res: Response) -> Dict[str, Any]: return cast(Dict[str, Any], res.json()) return executor.execute( response_callback=resp, method=self._connection.get, path=f"/schema/{self._name}", error_msg="Collection configuration could not be retrieved.", status_codes=_ExpectedStatusCodes(ok_in=200, error="Get collection configuration"), ) @overload def get( self, simple: Literal[False] = False, ) -> executor.Result[CollectionConfig]: ... @overload def get( self, simple: Literal[True], ) -> executor.Result[CollectionConfigSimple]: ... @overload def get( self, simple: bool = False, ) -> executor.Result[Union[CollectionConfig, CollectionConfigSimple]]: ... def get( self, simple: bool = False, ) -> executor.Result[Union[CollectionConfig, CollectionConfigSimple]]: """Get the configuration for this collection from Weaviate. Args: simple: If True, return a simplified version of the configuration containing only name and properties. Raises: weaviate.exceptions.WeaviateConnectionError: If the network connection to Weaviate fails. weaviate.exceptions.UnexpectedStatusCodeError: If Weaviate reports a non-OK status. """ _validate_input([_ValidateArgument(expected=[bool], name="simple", value=simple)]) def resp(res: Dict[str, Any]) -> Union[CollectionConfig, CollectionConfigSimple]: if simple: return _collection_config_simple_from_json(res) return _collection_config_from_json(res) return executor.execute( response_callback=resp, method=self.__get, ) def update( self, *, description: Optional[str] = None, property_descriptions: Optional[Dict[str, str]] = None, inverted_index_config: Optional[_InvertedIndexConfigUpdate] = None, multi_tenancy_config: Optional[_MultiTenancyConfigUpdate] = None, replication_config: Optional[_ReplicationConfigUpdate] = None, vector_index_config: Optional[ Union[ _VectorIndexConfigHNSWUpdate, _VectorIndexConfigFlatUpdate, ] ] = None, vectorizer_config: Optional[ Union[ _VectorIndexConfigHNSWUpdate, _VectorIndexConfigFlatUpdate, _VectorIndexConfigDynamicUpdate, List[_NamedVectorConfigUpdate], ] ] = None, vector_config: Optional[Union[_VectorConfigUpdate, List[_VectorConfigUpdate]]] = None, generative_config: Optional[_GenerativeProvider] = None, reranker_config: Optional[_RerankerProvider] = None, ) -> executor.Result[None]: """Update the configuration for this collection in Weaviate. Use the `weaviate.classes.Reconfigure` class to generate the necessary configuration objects for this method. Args: description: A description of the collection. inverted_index_config: Configuration for the inverted index. Use `Reconfigure.inverted_index` to generate one. replication_config: Configuration for the replication. Use `Reconfigure.replication` to generate one. reranker_config: Configuration for the reranker. Use `Reconfigure.replication` to generate one. vector_index_config (DEPRECATED use `vector_config`): Configuration for the vector index of the default single vector. Use `Reconfigure.vector_index` to generate one. vectorizer_config: Configurations for the vector index (or indices) of your collection. Use `Reconfigure.vector_index` if using legacy vectorization and `Reconfigure.NamedVectors` if you have many named vectors to generate them. Using this argument with a list of `Reconfigure.NamedVectors` is **DEPRECATED**. Use the `vector_config` argument instead in such a case. vector_config: Configuration for the vector index (or indices) of your collection. Use `Reconfigure.Vectors` for both single and multiple vectorizers. Supply a list to update many vectorizers at once. multi_tenancy_config: Configuration for multi-tenancy settings. Use `Reconfigure.multi_tenancy` to generate one. Only `auto_tenant_creation` is supported. Raises: weaviate.exceptions.WeaviateInvalidInputError: If the input parameters are invalid. weaviate.exceptions.WeaviateConnectionError: If the network connection to Weaviate fails. weaviate.exceptions.UnexpectedStatusCodeError: If Weaviate reports a non-OK status. NOTE: - If you wish to update a specific option within the configuration and cannot find it in `CollectionConfigUpdate` then it is an immutable option. - To change it, you will have to delete the collection and recreate it with the desired options. - This is not the case of adding properties, which can be done with `collection.config.add_property()`. """ if vector_index_config is not None: _Warnings.vector_index_config_in_config_update() if vectorizer_config is not None and not isinstance( vectorizer_config, ( _VectorIndexConfigHNSWUpdate, _VectorIndexConfigFlatUpdate, _VectorIndexConfigDynamicUpdate, ), ): _Warnings.vectorizer_config_in_config_update() try: config = _CollectionConfigUpdate( description=description, property_descriptions=property_descriptions, inverted_index_config=inverted_index_config, replication_config=replication_config, vector_index_config=vector_index_config, vectorizer_config=vectorizer_config, multi_tenancy_config=multi_tenancy_config, generative_config=generative_config, reranker_config=reranker_config, vector_config=vector_config, ) except ValidationError as e: raise WeaviateInvalidInputError("Invalid collection config update parameters.") from e def resp(schema: Dict[str, Any]) -> executor.Result[None]: schema = config.merge_with_existing(schema) def inner_resp(res: Response) -> None: return None return executor.execute( response_callback=inner_resp, method=self._connection.put, path=f"/schema/{self._name}", weaviate_object=schema, error_msg="Collection configuration may not have been updated.", status_codes=_ExpectedStatusCodes( ok_in=200, error="Update collection configuration" ), ) if isinstance(self._connection, ConnectionAsync): async def _execute() -> None: schema = await executor.aresult(self.__get()) return await executor.aresult(resp(schema)) return _execute() schema = executor.result(self.__get()) return executor.result(resp(schema)) def __add_property(self, additional_property: PropertyType) -> executor.Result[None]: path = f"/schema/{self._name}/properties" obj = additional_property._to_dict() def resp(schema: Dict[str, Any]) -> executor.Result[None]: modconf = {} if "skip_vectorization" in obj: modconf["skip"] = obj["skip_vectorization"] del obj["skip_vectorization"] if "vectorize_property_name" in obj: modconf["vectorizePropertyName"] = obj["vectorize_property_name"] del obj["vectorize_property_name"] module_config: Dict[str, Any] = schema.get("moduleConfig", {}) legacy_vectorizer = [ str(k) for k in module_config if "generative" not in k and "reranker" not in k ] if len(legacy_vectorizer) > 0 and len(modconf) > 0: obj["moduleConfig"] = {legacy_vectorizer[0]: modconf} vector_config: Dict[str, Any] = schema.get("vectorConfig", {}) if len(vector_config) > 0: obj["moduleConfig"] = { list(conf["vectorizer"].keys()).pop(): modconf for conf in vector_config.values() } def inner_resp(res: Response) -> None: return None return executor.execute( response_callback=inner_resp, method=self._connection.post, path=path, weaviate_object=obj, error_msg="Property may not have been added properly.", status_codes=_ExpectedStatusCodes(ok_in=200, error="Add property to collection"), ) if isinstance(self._connection, ConnectionAsync): async def _execute() -> None: schema = await executor.aresult(self.__get()) return await executor.aresult(resp(schema)) return _execute() schema = executor.result(self.__get()) return executor.result(resp(schema)) def __property_exists(self, property_name: str) -> executor.Result[bool]: def resp(schema: Dict[str, Any]) -> bool: conf = _collection_config_simple_from_json(schema) if len(conf.properties) == 0: return False for prop in conf.properties: if prop.name == property_name: return True return False return executor.execute( response_callback=resp, method=self.__get, ) def __reference_exists(self, reference_name: str) -> executor.Result[bool]: def resp(schema: Dict[str, Any]) -> bool: conf = _collection_config_simple_from_json(schema) if len(conf.references) == 0: return False for ref in conf.references: if ref.name == reference_name: return True return False return executor.execute( response_callback=resp, method=self.__get, ) def __get_shards(self) -> executor.Result[List[ShardStatus]]: def resp(res: Response) -> List[ShardStatus]: shards = _decode_json_response_list(res, "get shards") assert shards is not None return [ _ShardStatus( name=shard["name"], status=shard["status"], vector_queue_size=shard["vectorQueueSize"], ) for shard in shards ] return executor.execute( response_callback=resp, method=self._connection.get, path=f"/schema/{self._name}/shards{f'?tenant={self._tenant}' if self._tenant else ''}", error_msg="Shard statuses could not be retrieved.", ) def get_shards(self) -> executor.Result[List[ShardStatus]]: """Get the statuses of the shards of this collection. If the collection is multi-tenancy and you did not call `.with_tenant` then you will receive the statuses of all the tenants within the collection. Otherwise, call `.with_tenant` on the collection first and you will receive only that single shard. Returns: A list of objects containing the statuses of the shards. Raises: weaviate.exceptions.WeaviateConnectionError: If the network connection to Weaviate fails. weaviate.exceptions.UnexpectedStatusCodeError: If Weaviate reports a non-OK status. """ return self.__get_shards() def __update_shard( self, shard_name: str, status: str ) -> executor.Result[Tuple[str, ShardTypes]]: path = f"/schema/{self._name}/shards/{shard_name}" data = {"status": status} def resp(res: Response) -> Tuple[str, ShardTypes]: shard = _decode_json_response_dict(res, f"Update shard '{shard_name}' status") assert shard is not None return shard_name, shard["status"] return executor.execute( response_callback=resp, method=self._connection.put, path=path, weaviate_object=data, error_msg=f"shard '{shard_name}' may not have been updated.", ) def update_shards( self, status: Literal["READY", "READONLY"], shard_names: Optional[Union[str, List[str]]] = None, ) -> executor.Result[Dict[str, ShardTypes]]: """Update the status of one or all shards of this collection. Args: status: The new status of the shard. The available options are: 'READY' and 'READONLY'. shard_name: The shard name for which to update the status of the class of the shard. If None all shards are going to be updated. Returns: All updated shards indexed by their name. Raises: weaviate.exceptions.WeaviateConnectionError: If the network connection to Weaviate fails. weaviate.exceptions.UnexpectedStatusCodeError: If Weaviate reports a non-OK status. """ if isinstance(self._connection, ConnectionAsync): async def _execute( shard_names: Optional[Union[str, List[str]]], ) -> Dict[str, ShardTypes]: if shard_names is None: shards_config = await executor.aresult(self.__get_shards()) shard_names = [shard_config.name for shard_config in shards_config] elif isinstance(shard_names, str): shard_names = [shard_names] results = await asyncio.gather( *[ executor.aresult(self.__update_shard(shard_name=shard_name, status=status)) for shard_name in shard_names ] ) return {result[0]: result[1] for result in results} return _execute(shard_names) if shard_names is None: shards_config = executor.result(self.__get_shards()) shard_names = [shard_config.name for shard_config in shards_config] elif isinstance(shard_names, str): shard_names = [shard_names] return { result[0]: result[1] for result in [ executor.result(self.__update_shard(shard_name=shard_name, status=status)) for shard_name in shard_names ] } def add_property(self, prop: Property) -> executor.Result[None]: """Add a property to the collection in Weaviate. Args: prop: The property to add to the collection. Raises: weaviate.exceptions.WeaviateConnectionError: If the network connection to Weaviate fails. weaviate.exceptions.UnexpectedStatusCodeError: If Weaviate reports a non-OK status. weaviate.exceptions.WeaviateInvalidInputError: If the property already exists in the collection. """ _validate_input([_ValidateArgument(expected=[Property], name="prop", value=prop)]) def resp(exists: bool) -> executor.Result[None]: if exists: raise WeaviateInvalidInputError( f"Property with name '{prop.name}' already exists in collection '{self._name}'." ) return self.__add_property(additional_property=prop) if isinstance(self._connection, ConnectionAsync): async def _execute() -> None: exists = await executor.aresult(self.__property_exists(property_name=prop.name)) return await executor.aresult(resp(exists)) return _execute() exists = executor.result(self.__property_exists(property_name=prop.name)) return executor.result(resp(exists)) def add_reference( self, ref: Union[ReferenceProperty, _ReferencePropertyMultiTarget], ) -> executor.Result[None]: """Add a reference to the collection in Weaviate. Args: ref: The reference to add to the collection. Raises: weaviate.exceptions.WeaviateConnectionError: If the network connection to Weaviate fails. weaviate.exceptions.UnexpectedStatusCodeError: If Weaviate reports a non-OK status. weaviate.exceptions.WeaviateInvalidInputError: If the reference already exists in the collection. """ _validate_input( [ _ValidateArgument( expected=[ReferenceProperty, _ReferencePropertyMultiTarget], name="ref", value=ref, ) ] ) def resp(exists: bool) -> executor.Result[None]: if exists: raise WeaviateInvalidInputError( f"Reference with name '{ref.name}' already exists in collection '{self._name}'." ) return self.__add_property(additional_property=ref) if isinstance(self._connection, ConnectionAsync): async def _execute() -> None: exists = await executor.aresult(self.__reference_exists(reference_name=ref.name)) return await executor.aresult(resp(exists)) return _execute() exists = executor.result(self.__reference_exists(reference_name=ref.name)) return executor.result(resp(exists)) @overload @deprecated( "Using `Configure.NamedVectors` in `vector_config` is deprecated. Instead, use `Configure.Vectors` or `Configure.MultiVectors`." ) def add_vector( self, *, vector_config: Union[_NamedVectorConfigCreate, List[_NamedVectorConfigCreate]] ) -> executor.Result[None]: ... @overload def add_vector( self, *, vector_config: Union[_VectorConfigCreate, List[_VectorConfigCreate]] ) -> executor.Result[None]: ... def add_vector( self, *, vector_config: Union[ _NamedVectorConfigCreate, _VectorConfigCreate, List[_NamedVectorConfigCreate], List[_VectorConfigCreate], ], ) -> executor.Result[None]: """Add a vector to the collection in Weaviate. Args: vector_config: The vector configuration to add to the collection. Raises: weaviate.exceptions.WeaviateConnectionError: If the network connection to Weaviate fails. weaviate.exceptions.UnexpectedStatusCodeError: If Weaviate reports a non-OK status. weaviate.exceptions.WeaviateInvalidInputError: If the vector already exists in the collection. """ _validate_input( [ _ValidateArgument( expected=[ _NamedVectorConfigCreate, _VectorConfigCreate, List[_NamedVectorConfigCreate], List[_VectorConfigCreate], ], name="vector_config", value=vector_config, ) ] ) if isinstance(vector_config, list): for c in vector_config: if isinstance(c, _NamedVectorConfigCreate): _Warnings.named_vector_syntax_in_config_add_vector(c.name) if c.name is None: raise WeaviateInvalidInputError( "The configured vector must have a name when adding it to a collection." ) if isinstance(vector_config, _NamedVectorConfigCreate): _Warnings.named_vector_syntax_in_config_add_vector(vector_config.name) vector_config = [vector_config] if isinstance(vector_config, _VectorConfigCreate): vector_config = [vector_config] def resp(schema: Dict[str, Any]) -> executor.Result[None]: if "vectorConfig" not in schema: schema["vectorConfig"] = {} for vector in vector_config: schema["vectorConfig"][vector.name] = vector._to_dict() return executor.execute( response_callback=lambda _: None, method=self._connection.put, path=f"/schema/{self._name}", weaviate_object=schema, error_msg="Collection configuration may not have been updated.", status_codes=_ExpectedStatusCodes( ok_in=200, error="Update collection configuration" ), ) if isinstance(self._connection, ConnectionAsync): async def _execute() -> None: schema = await executor.aresult(self.__get()) return await executor.aresult(resp(schema)) return _execute() schema = executor.result(self.__get()) return executor.result(resp(schema))
_ConfigCollectionExecutor
python
pdm-project__pdm
src/pdm/cli/commands/venv/create.py
{ "start": 192, "end": 2156 }
class ____(BaseCommand): """Create a virtualenv pdm venv create <python> [-other args] """ description = "Create a virtualenv" arguments = (verbose_option,) def add_arguments(self, parser: argparse.ArgumentParser) -> None: parser.add_argument( "-w", "--with", dest="backend", choices=BACKENDS.keys(), help="Specify the backend to create the virtualenv", ) parser.add_argument( "-f", "--force", action="store_true", help="Recreate if the virtualenv already exists", ) parser.add_argument("-n", "--name", help="Specify the name of the virtualenv") parser.add_argument("--with-pip", action="store_true", help="Install pip with the virtualenv") parser.add_argument( "python", nargs="?", help="Specify which python should be used to create the virtualenv", ) parser.add_argument( "venv_args", nargs=argparse.REMAINDER, help="Additional arguments that will be passed to the backend", ) def handle(self, project: Project, options: argparse.Namespace) -> None: in_project = project.config["venv.in_project"] and not options.name backend: str = options.backend or project.config["venv.backend"] venv_backend = BACKENDS[backend](project, options.python) with project.core.ui.open_spinner(f"Creating virtualenv using [success]{backend}[/]..."): path = venv_backend.create( options.name, options.venv_args, options.force, in_project, prompt=project.config["venv.prompt"], with_pip=options.with_pip or project.config["venv.with_pip"], ) project.core.ui.echo(f"Virtualenv [success]{path}[/] is created successfully")
CreateCommand
python
bokeh__bokeh
src/bokeh/server/tornado.py
{ "start": 3019, "end": 31887 }
class ____(TornadoApplication): ''' A Tornado Application used to implement the Bokeh Server. Args: applications (dict[str,Application] or Application) : A map from paths to ``Application`` instances. If the value is a single Application, then the following mapping is generated: .. code-block:: python applications = {{ '/' : applications }} When a connection comes in to a given path, the associate Application is used to generate a new document for the session. prefix (str, optional) : A URL prefix to use for all Bokeh server paths. (default: None) ico_path (str, optional) : A path to a .ico file to return for ``/favicon.ico``. extra_websocket_origins (list[str], optional) : A list of hosts that can connect to the websocket. This is typically required when embedding a Bokeh server app in an external web site using :func:`~bokeh.embed.server_document` or similar. If None, ``["localhost"]`` will be assumed (default: None) extra_patterns (seq[tuple], optional) : A list of tuples of (str, http or websocket handler) Use this argument to add additional endpoints to custom deployments of the Bokeh Server. If None, then ``[]`` will be used. (default: None) secret_key (str, optional) : A secret key for signing session IDs. Defaults to the current value of the environment variable ``BOKEH_SECRET_KEY`` sign_sessions (bool, optional) : Whether to cryptographically sign session IDs Defaults to the current value of the environment variable ``BOKEH_SIGN_SESSIONS``. If ``True``, then ``secret_key`` must also be provided (either via environment setting or passed as a parameter value) generate_session_ids (bool, optional) : Whether to generate a session ID if one is not provided (default: True) keep_alive_milliseconds (int, optional) : Number of milliseconds between keep-alive pings (default: {DEFAULT_KEEP_ALIVE_MS}) Pings normally required to keep the websocket open. Set to 0 to disable pings. check_unused_sessions_milliseconds (int, optional) : Number of milliseconds between checking for unused sessions (default: {DEFAULT_CHECK_UNUSED_MS}) unused_session_lifetime_milliseconds (int, optional) : Number of milliseconds for unused session lifetime (default: {DEFAULT_UNUSED_LIFETIME_MS}) stats_log_frequency_milliseconds (int, optional) : Number of milliseconds between logging stats (default: {DEFAULT_STATS_LOG_FREQ_MS}) mem_log_frequency_milliseconds (int, optional) : Number of milliseconds between logging memory information (default: {DEFAULT_MEM_LOG_FREQ_MS}) Enabling this feature requires the optional dependency ``psutil`` to be installed. use_index (bool, optional) : Whether to generate an index of running apps in the ``RootHandler`` (default: True) index (str, optional) : Path to a Jinja2 template to serve as the index for "/" if use_index is True. If None, the basic built in app index template is used. (default: None) redirect_root (bool, optional) : When there is only a single running application, whether to redirect requests to ``"/"`` to that application automatically (default: True) If there are multiple Bokeh applications configured, this option has no effect. websocket_max_message_size_bytes (int, optional): Set the Tornado ``websocket_max_message_size`` value. (default: {DEFAULT_WEBSOCKET_MAX_MESSAGE_SIZE_BYTES}) websocket_compression_level (int, optional): Set the Tornado WebSocket ``compression_level`` documented in https://docs.python.org/3.7/library/zlib.html#zlib.compressobj. websocket_compression_mem_level (int, optional): Set the Tornado WebSocket compression ``mem_level`` documented in https://docs.python.org/3.7/library/zlib.html#zlib.compressobj. index (str, optional): Path to a Jinja2 template to use for the root URL auth_provider (AuthProvider, optional): An AuthProvider instance include_headers (list, optional) : List of request headers to include in session context (by default all headers are included) exclude_headers (list, optional) : List of request headers to exclude in session context (by default all headers are included) include_cookies (list, optional) : List of cookies to include in session context (by default all cookies are included) exclude_cookies (list, optional) : List of cookies to exclude in session context (by default all cookies are included) session_token_expiration (int, optional) : Duration in seconds that a new session token is valid for session creation. After the expiry time has elapsed, the token will not be able create a new session (default: {DEFAULT_SESSION_TOKEN_EXPIRATION}) Any additional keyword arguments are passed to ``tornado.web.Application``. ''' _loop: IOLoop _applications: Mapping[str, ApplicationContext] _prefix: str _websocket_origins: set[str] auth_provider: AuthProvider _clients: set[ServerConnection] _mem_job: PeriodicCallback | None _ping_job: PeriodicCallback | None def __init__(self, applications: Mapping[str, Application | ModifyDoc] | Application | ModifyDoc, *, absolute_url: str | None = None, prefix: str | None = None, extra_websocket_origins: Sequence[str] | None = None, extra_patterns: URLRoutes | None = None, secret_key: bytes | None = settings.secret_key_bytes(), sign_sessions: bool = settings.sign_sessions(), generate_session_ids: bool = True, keep_alive_milliseconds: int = DEFAULT_KEEP_ALIVE_MS, check_unused_sessions_milliseconds: int = DEFAULT_CHECK_UNUSED_MS, unused_session_lifetime_milliseconds: int = DEFAULT_UNUSED_LIFETIME_MS, stats_log_frequency_milliseconds: int = DEFAULT_STATS_LOG_FREQ_MS, mem_log_frequency_milliseconds: int = DEFAULT_MEM_LOG_FREQ_MS, use_index: bool = True, redirect_root: bool = True, websocket_max_message_size_bytes: int = DEFAULT_WEBSOCKET_MAX_MESSAGE_SIZE_BYTES, websocket_compression_level: int | None = None, websocket_compression_mem_level: int | None = None, ico_path: str = settings.ico_path(), index: str | None = None, auth_provider: AuthProvider = NullAuth(), xsrf_cookies: bool = False, include_headers: list[str] | None = None, include_cookies: list[str] | None = None, exclude_headers: list[str] | None = None, exclude_cookies: list[str] | None = None, session_token_expiration: int = DEFAULT_SESSION_TOKEN_EXPIRATION, **kwargs: Any): from ..application.handlers.document_lifecycle import DocumentLifecycleHandler from ..application.handlers.function import FunctionHandler if callable(applications): applications = Application(FunctionHandler(applications)) if isinstance(applications, Application): applications = {'/' : applications} else: applications = dict(applications) for url, app in list(applications.items()): if callable(app): applications[url] = app = Application(FunctionHandler(app)) if all(not isinstance(handler, DocumentLifecycleHandler) for handler in app._handlers): app.add(DocumentLifecycleHandler()) self._absolute_url = absolute_url if prefix is None: prefix = "" prefix = prefix.strip("/") if prefix: prefix = "/" + prefix self._prefix = prefix self._index = index if keep_alive_milliseconds < 0: # 0 means "disable" raise ValueError("keep_alive_milliseconds must be >= 0") else: if keep_alive_milliseconds == 0: log.info("Keep-alive ping disabled") elif keep_alive_milliseconds != DEFAULT_KEEP_ALIVE_MS: log.info("Keep-alive ping configured every %d milliseconds", keep_alive_milliseconds) self._keep_alive_milliseconds = keep_alive_milliseconds if check_unused_sessions_milliseconds <= 0: raise ValueError("check_unused_sessions_milliseconds must be > 0") elif check_unused_sessions_milliseconds != DEFAULT_CHECK_UNUSED_MS: log.info("Check for unused sessions every %d milliseconds", check_unused_sessions_milliseconds) self._check_unused_sessions_milliseconds = check_unused_sessions_milliseconds if unused_session_lifetime_milliseconds <= 0: raise ValueError("unused_session_lifetime_milliseconds must be > 0") elif unused_session_lifetime_milliseconds != DEFAULT_UNUSED_LIFETIME_MS: log.info("Unused sessions last for %d milliseconds", unused_session_lifetime_milliseconds) self._unused_session_lifetime_milliseconds = unused_session_lifetime_milliseconds if stats_log_frequency_milliseconds <= 0: raise ValueError("stats_log_frequency_milliseconds must be > 0") elif stats_log_frequency_milliseconds != DEFAULT_STATS_LOG_FREQ_MS: log.info("Log statistics every %d milliseconds", stats_log_frequency_milliseconds) self._stats_log_frequency_milliseconds = stats_log_frequency_milliseconds if mem_log_frequency_milliseconds < 0: # 0 means "disable" raise ValueError("mem_log_frequency_milliseconds must be >= 0") elif mem_log_frequency_milliseconds > 0: if psutil is None: log.warning("Memory logging requested, but is disabled. Optional dependency 'psutil' is missing. " "Try 'pip install psutil' or 'conda install psutil'") mem_log_frequency_milliseconds = 0 elif mem_log_frequency_milliseconds != DEFAULT_MEM_LOG_FREQ_MS: log.info("Log memory usage every %d milliseconds", mem_log_frequency_milliseconds) self._mem_log_frequency_milliseconds = mem_log_frequency_milliseconds if websocket_max_message_size_bytes <= 0: raise ValueError("websocket_max_message_size_bytes must be positive") elif websocket_max_message_size_bytes != DEFAULT_WEBSOCKET_MAX_MESSAGE_SIZE_BYTES: log.info("Torndado websocket_max_message_size set to %d bytes (%0.2f MB)", websocket_max_message_size_bytes, websocket_max_message_size_bytes/1024.0**2) self.auth_provider = auth_provider if self.auth_provider.get_user or self.auth_provider.get_user_async: log.info("User authentication hooks provided (no default user)") else: log.info("User authentication hooks NOT provided (default user enabled)") kwargs['xsrf_cookies'] = xsrf_cookies if xsrf_cookies: log.info("XSRF cookie protection enabled") if session_token_expiration <= 0: raise ValueError("session_token_expiration must be > 0") else: self._session_token_expiration = session_token_expiration if exclude_cookies and include_cookies: raise ValueError("Declare either an include or an exclude list for the cookies, not both.") self._exclude_cookies = exclude_cookies self._include_cookies = include_cookies if exclude_headers and include_headers: raise ValueError("Declare either an include or an exclude list for the headers, not both.") self._exclude_headers = exclude_headers self._include_headers = include_headers if extra_websocket_origins is None: self._websocket_origins = set() else: self._websocket_origins = set(extra_websocket_origins) self._secret_key = secret_key self._sign_sessions = sign_sessions self._generate_session_ids = generate_session_ids log.debug(f"These host origins can connect to the websocket: {list(self._websocket_origins)!r}") # Wrap applications in ApplicationContext self._applications = {} for url, app in applications.items(): assert isinstance(app, Application) # TODO: unnecessary; improve type flow to remove this self._applications[url] = ApplicationContext(app, url=url, logout_url=self.auth_provider.logout_url) extra_patterns = extra_patterns or [] extra_patterns.extend(self.auth_provider.endpoints) if ico_path == "none": self._icon = None else: with open(ico_path, 'rb') as f: self._icon = f.read() all_patterns: URLRoutes = [(r'/favicon.ico', IcoHandler, dict(app=self))] for key, ctx in self._applications.items(): app_patterns: URLRoutes = [] for p in per_app_patterns: if key == "/": route = p[0] else: route = key + p[0] context: RouteContext = {"application_context": self._applications[key]} if issubclass(p[1], WSHandler): context['compression_level'] = websocket_compression_level context['mem_level'] = websocket_compression_mem_level route = self._prefix + route app_patterns.append((route, p[1], context)) websocket_path = None for r in app_patterns: if r[0].endswith("/ws"): websocket_path = r[0] if not websocket_path: raise RuntimeError("Couldn't find websocket path") for r in app_patterns: assert len(r) == 3 # TODO: handle two valued case as well r[2]["bokeh_websocket_path"] = websocket_path all_patterns.extend(app_patterns) # if the app requests a custom static path, use that, otherwise add Bokeh's standard static handler all_patterns.append(create_static_handler(self._prefix, key, ctx.application)) for p in extra_patterns + toplevel_patterns: if p[1] == RootHandler: if use_index: data = { "applications": self._applications, "prefix": self._prefix, "index": self._index, "use_redirect": redirect_root, } prefixed_pat = (self._prefix + p[0], *p[1:], data) all_patterns.append(prefixed_pat) else: prefixed_pat = (self._prefix + p[0], *p[1:]) all_patterns.append(prefixed_pat) log.debug("Patterns are:") for line in pformat(all_patterns, width=60).split("\n"): log.debug(" " + line) super().__init__(all_patterns, websocket_max_message_size=websocket_max_message_size_bytes, **kwargs) def initialize(self, io_loop: IOLoop) -> None: ''' Start a Bokeh Server Tornado Application on a given Tornado IOLoop. ''' self._loop = io_loop for app_context in self._applications.values(): app_context._loop = self._loop self._clients = set() self._stats_job = PeriodicCallback(self._log_stats, self._stats_log_frequency_milliseconds) if self._mem_log_frequency_milliseconds > 0: self._mem_job = PeriodicCallback(self._log_mem, self._mem_log_frequency_milliseconds) else: self._mem_job = None self._cleanup_job = PeriodicCallback(self._cleanup_sessions, self._check_unused_sessions_milliseconds) if self._keep_alive_milliseconds > 0: self._ping_job = PeriodicCallback(self._keep_alive, self._keep_alive_milliseconds) else: self._ping_job = None @property def applications(self) -> Mapping[str, ApplicationContext]: ''' The configured applications ''' return self._applications @property def app_paths(self) -> set[str]: ''' A list of all application paths for all Bokeh applications configured on this Bokeh server instance. ''' return set(self._applications) @property def index(self) -> str | None: ''' Path to a Jinja2 template to serve as the index "/" ''' return self._index @property def icon(self) -> bytes | None: ''' Favicon.ico file data, or None ''' return self._icon @property def io_loop(self) -> IOLoop: ''' The Tornado IOLoop that this Bokeh Server Tornado Application is running on. ''' return self._loop @property def prefix(self) -> str: ''' A URL prefix for this Bokeh Server Tornado Application to use for all paths ''' return self._prefix @property def websocket_origins(self) -> set[str]: ''' A list of websocket origins permitted to connect to this server. ''' return self._websocket_origins @property def secret_key(self) -> bytes | None: ''' A secret key for this Bokeh Server Tornado Application to use when signing session IDs, if configured. ''' return self._secret_key @property def include_cookies(self) -> list[str] | None: ''' A list of request cookies to make available in the session context. ''' return self._include_cookies @property def include_headers(self) -> list[str] | None: ''' A list of request headers to make available in the session context. ''' return self._include_headers @property def exclude_cookies(self) -> list[str] | None: ''' A list of request cookies to exclude in the session context. ''' return self._exclude_cookies @property def exclude_headers(self) -> list[str] | None: ''' A list of request headers to exclude in the session context. ''' return self._exclude_headers @property def sign_sessions(self) -> bool: ''' Whether this Bokeh Server Tornado Application has been configured to cryptographically sign session IDs If ``True``, then ``secret_key`` must also have been configured. ''' return self._sign_sessions @property def generate_session_ids(self) -> bool: ''' Whether this Bokeh Server Tornado Application has been configured to automatically generate session IDs. ''' return self._generate_session_ids @property def session_token_expiration(self) -> int: ''' Duration in seconds that a new session token is valid for session creation. After the expiry time has elapsed, the token will not be able create a new session. ''' return self._session_token_expiration def resources(self, absolute_url: str | bool | None = None) -> Resources: ''' Provide a :class:`~bokeh.resources.Resources` that specifies where Bokeh application sessions should load BokehJS resources from. Args: absolute_url (str, bool): An absolute URL prefix to use for locating resources. If ``True``, a prefix consisting of server's protocol, host and port will be used. Otherwise, root-relative URLs are used (default: ``None``) ''' mode = settings.resources(default="server") if mode == "server" or mode == "server-dev": if absolute_url is True: absolute_url = self._absolute_url if absolute_url is None or absolute_url is False: absolute_url = "/" root_url = urljoin(absolute_url, self._prefix) return Resources(mode=mode, root_url=root_url, path_versioner=StaticHandler.append_version) return Resources(mode=mode) def start(self) -> None: ''' Start the Bokeh Server application. Starting the Bokeh Server Tornado application will run periodic callbacks for stats logging, cleanup, pinging, etc. Additionally, any startup hooks defined by the configured Bokeh applications will be run. ''' self._stats_job.start() if self._mem_job is not None: self._mem_job.start() self._cleanup_job.start() if self._ping_job is not None: self._ping_job.start() for context in self._applications.values(): self._loop.add_callback(context.run_load_hook) def stop(self, wait: bool = True) -> None: ''' Stop the Bokeh Server application. Args: wait (bool): whether to wait for orderly cleanup (default: True) Returns: None ''' # TODO should probably close all connections and shut down all sessions here for context in self._applications.values(): context.run_unload_hook() self._stats_job.stop() if self._mem_job is not None: self._mem_job.stop() self._cleanup_job.stop() if self._ping_job is not None: self._ping_job.stop() self._clients.clear() def new_connection(self, protocol: Protocol, socket: WSHandler, application_context: ApplicationContext, session: ServerSession) -> ServerConnection: connection = ServerConnection(protocol, socket, application_context, session) self._clients.add(connection) return connection def client_lost(self, connection: ServerConnection) -> None: self._clients.discard(connection) connection.detach_session() def get_session(self, app_path: str, session_id: ID) -> ServerSession: ''' Get an active a session by name application path and session ID. Args: app_path (str) : The configured application path for the application to return a session for. session_id (str) : The session ID of the session to retrieve. Returns: ServerSession ''' if app_path not in self._applications: raise ValueError(f"Application {app_path} does not exist on this server") return self._applications[app_path].get_session(session_id) def get_sessions(self, app_path: str) -> list[ServerSession]: ''' Gets all currently active sessions for an application. Args: app_path (str) : The configured application path for the application to return sessions for. Returns: list[ServerSession] ''' if app_path not in self._applications: raise ValueError(f"Application {app_path} does not exist on this server") return list(self._applications[app_path].sessions) # Periodic Callbacks ------------------------------------------------------ async def _cleanup_sessions(self) -> None: log.trace("Running session cleanup job") # type: ignore[attr-defined] for app in self._applications.values(): await app._cleanup_sessions(self._unused_session_lifetime_milliseconds) return None def _log_stats(self) -> None: log.trace("Running stats log job") # type: ignore[attr-defined] if log.getEffectiveLevel() > logging.DEBUG: # avoid the work below if we aren't going to log anything return log.debug("[pid %d] %d clients connected", PID, len(self._clients)) for app_path, app in self._applications.items(): sessions = list(app.sessions) unused_count = 0 for s in sessions: if s.connection_count == 0: unused_count += 1 log.debug("[pid %d] %s has %d sessions with %d unused", PID, app_path, len(sessions), unused_count) def _log_mem(self) -> None: # we should be able to assume PROC is define, if psutil is not installed # then the _log_mem callback is not started at all mem = PROC.memory_info() log.info("[pid %d] Memory usage: %0.2f MB (RSS), %0.2f MB (VMS)", PID, mem.rss/GB, mem.vms/GB) del mem # skip the rest if we would not log it anyway if log.getEffectiveLevel() > logging.DEBUG: return #from collections import Counter # pprint.pprint(Counter([str(type(x)) for x in gc.get_objects() if "DataFrame" in str(type(x))]).most_common(30)) all_objs = gc.get_objects() from ..document import Document from .session import ServerSession for name, typ in [('Documents', Document), ('Sessions', ServerSession), ('Models', Model)]: objs = [x for x in all_objs if isinstance(x, typ)] log.debug(f" uncollected {name}: {len(objs)}") # uncomment for potentially voluminous referrers output # if name == 'Models' and len(objs): # import pprint # for i in range(10): # print(i, objs[i], gc.get_referents(objs[i])) from types import ModuleType objs = [x for x in gc.get_objects() if isinstance(x, ModuleType) and "bokeh_app_" in str(x)] log.debug(f" uncollected modules: {len(objs)}") if pd := sys.modules.get("pandas"): objs = [x for x in all_objs if isinstance(x, pd.DataFrame)] log.debug(" uncollected DataFrames: %d", len(objs)) # uncomment (and install pympler) for mem usage by type report # from operator import itemgetter # import pprint # from pympler import tracker # mem = tracker.SummaryTracker() # pprint.pprint(sorted(mem.create_summary(), reverse=True, key=itemgetter(2))[:30]) def _keep_alive(self) -> None: log.trace("Running keep alive job") # type: ignore[attr-defined] for c in list(self._clients): try: c.send_ping() except WebSocketClosedError: self.client_lost(c) #----------------------------------------------------------------------------- # Dev API #----------------------------------------------------------------------------- def create_static_handler(prefix: str, key: str, app: Application) -> tuple[str, type[StaticFileHandler | StaticHandler], dict[str, Any]]: route = prefix route += "/static/(.*)" if key == "/" else key + "/static/(.*)" if app.static_path is not None: return (route, StaticFileHandler, {"path" : app.static_path}) return (route, StaticHandler, {}) #----------------------------------------------------------------------------- # Private API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Code #----------------------------------------------------------------------------- BokehTornado.__doc__ = format_docstring( BokehTornado.__doc__, DEFAULT_CHECK_UNUSED_MS=DEFAULT_CHECK_UNUSED_MS, DEFAULT_KEEP_ALIVE_MS=DEFAULT_KEEP_ALIVE_MS, DEFAULT_MEM_LOG_FREQ_MS=DEFAULT_MEM_LOG_FREQ_MS, DEFAULT_STATS_LOG_FREQ_MS=DEFAULT_STATS_LOG_FREQ_MS, DEFAULT_UNUSED_LIFETIME_MS=DEFAULT_UNUSED_LIFETIME_MS, DEFAULT_WEBSOCKET_MAX_MESSAGE_SIZE_BYTES=DEFAULT_WEBSOCKET_MAX_MESSAGE_SIZE_BYTES, DEFAULT_SESSION_TOKEN_EXPIRATION=DEFAULT_SESSION_TOKEN_EXPIRATION, )
BokehTornado
python
allegroai__clearml
clearml/backend_api/services/v2_23/frames.py
{ "start": 173337, "end": 176515 }
class ____(Response): """ Response of frames.get_count_for_dataview_id endpoint. :param total: Total count of frames for the entire query. :type total: int :param rules: Specific information for each rule of this query. :type rules: Sequence[RuleCount] """ _service = "frames" _action = "get_count_for_dataview_id" _version = "2.23" _schema = { "definitions": { "rule_count": { "properties": { "accurate": { "description": ( "True if the provided count is accurate. If False, 'reason' will contain the reason why." ), "type": ["boolean", "null"], }, "count": { "description": "Number of frames matching this rule", "type": ["integer", "null"], }, "name": {"description": "Rule name", "type": ["string", "null"]}, "reason": { "description": "Reason for the count being inaccurate if 'accurate' is True, empty otherwise.", "type": ["string", "null"], }, "rule_index": { "description": "Rule index", "type": ["integer", "null"], }, }, "type": "object", } }, "properties": { "rules": { "description": "Specific information for each rule of this query.", "items": {"$ref": "#/definitions/rule_count"}, "type": ["array", "null"], }, "total": { "description": "Total count of frames for the entire query.", "type": ["integer", "null"], }, }, "type": "object", } def __init__(self, total=None, rules=None, **kwargs): super(GetCountForDataviewIdResponse, self).__init__(**kwargs) self.total = total self.rules = rules @schema_property("total") def total(self): return self._property_total @total.setter def total(self, value): if value is None: self._property_total = None return if isinstance(value, float) and value.is_integer(): value = int(value) self.assert_isinstance(value, "total", six.integer_types) self._property_total = value @schema_property("rules") def rules(self): return self._property_rules @rules.setter def rules(self, value): if value is None: self._property_rules = None return self.assert_isinstance(value, "rules", (list, tuple)) if any(isinstance(v, dict) for v in value): value = [ RuleCount.from_dict(v) if isinstance(v, dict) else v for v in value ] else: self.assert_isinstance(value, "rules", RuleCount, is_array=True) self._property_rules = value
GetCountForDataviewIdResponse
python
facebook__pyre-check
source/interprocedural_analyses/taint/test/integration/always_in_none.py
{ "start": 294, "end": 877 }
class ____: def serve_tainted_request(self): return "Valid" def test(complicated_service: ComplicatedService): exception = False result = None try: result = complicated_service.serve_tainted_request() except: exception = True # Only try reactivation if all other checks passed if exception: try: result = complicated_service.serve_tainted_request() except: raise _test_sink(result) def test_none_clears_taint(): x = _test_source() x = None _test_sink(x)
ComplicatedService
python
great-expectations__great_expectations
great_expectations/types/configurations.py
{ "start": 77, "end": 520 }
class ____: """Defines information sufficient to identify a class to be (dynamically) loaded for a DataContext.""" # noqa: E501 # FIXME CoP def __init__(self, class_name, module_name=None) -> None: self._class_name = class_name self._module_name = module_name @property def class_name(self): return self._class_name @property def module_name(self): return self._module_name
ClassConfig
python
matplotlib__matplotlib
lib/matplotlib/dates.py
{ "start": 39869, "end": 42120 }
class ____(DateLocator): # use the dateutil rrule instance def __init__(self, o, tz=None): super().__init__(tz) self.rule = o def __call__(self): # if no data have been set, this will tank with a ValueError try: dmin, dmax = self.viewlim_to_dt() except ValueError: return [] return self.tick_values(dmin, dmax) def tick_values(self, vmin, vmax): start, stop = self._create_rrule(vmin, vmax) dates = self.rule.between(start, stop, True) if len(dates) == 0: return date2num([vmin, vmax]) return self.raise_if_exceeds(date2num(dates)) def _create_rrule(self, vmin, vmax): # set appropriate rrule dtstart and until and return # start and end delta = relativedelta(vmax, vmin) # We need to cap at the endpoints of valid datetime try: start = vmin - delta except (ValueError, OverflowError): # cap start = datetime.datetime(1, 1, 1, 0, 0, 0, tzinfo=datetime.timezone.utc) try: stop = vmax + delta except (ValueError, OverflowError): # cap stop = datetime.datetime(9999, 12, 31, 23, 59, 59, tzinfo=datetime.timezone.utc) self.rule.set(dtstart=start, until=stop) return vmin, vmax def _get_unit(self): # docstring inherited freq = self.rule._rrule._freq return self.get_unit_generic(freq) @staticmethod def get_unit_generic(freq): if freq == YEARLY: return DAYS_PER_YEAR elif freq == MONTHLY: return DAYS_PER_MONTH elif freq == WEEKLY: return DAYS_PER_WEEK elif freq == DAILY: return 1.0 elif freq == HOURLY: return 1.0 / HOURS_PER_DAY elif freq == MINUTELY: return 1.0 / MINUTES_PER_DAY elif freq == SECONDLY: return 1.0 / SEC_PER_DAY else: # error return -1 # or should this just return '1'? def _get_interval(self): return self.rule._rrule._interval
RRuleLocator
python
plotly__plotly.py
plotly/graph_objs/sankey/node/hoverlabel/_font.py
{ "start": 233, "end": 17163 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "sankey.node.hoverlabel" _path_str = "sankey.node.hoverlabel.font" _valid_props = { "color", "colorsrc", "family", "familysrc", "lineposition", "linepositionsrc", "shadow", "shadowsrc", "size", "sizesrc", "style", "stylesrc", "textcase", "textcasesrc", "variant", "variantsrc", "weight", "weightsrc", } @property def color(self): """ The 'color' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: see https://plotly.com/python/css-colors/ for a list - A list or array of any of the above Returns ------- str|numpy.ndarray """ return self["color"] @color.setter def color(self, val): self["color"] = val @property def colorsrc(self): """ Sets the source reference on Chart Studio Cloud for `color`. The 'colorsrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["colorsrc"] @colorsrc.setter def colorsrc(self, val): self["colorsrc"] = val @property def family(self): """ HTML font family - the typeface that will be applied by the web browser. The web browser can only apply a font if it is available on the system where it runs. Provide multiple font families, separated by commas, to indicate the order in which to apply fonts if they aren't available. The 'family' property is a string and must be specified as: - A non-empty string - A tuple, list, or one-dimensional numpy array of the above Returns ------- str|numpy.ndarray """ return self["family"] @family.setter def family(self, val): self["family"] = val @property def familysrc(self): """ Sets the source reference on Chart Studio Cloud for `family`. The 'familysrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["familysrc"] @familysrc.setter def familysrc(self, val): self["familysrc"] = val @property def lineposition(self): """ Sets the kind of decoration line(s) with text, such as an "under", "over" or "through" as well as combinations e.g. "under+over", etc. The 'lineposition' property is a flaglist and may be specified as a string containing: - Any combination of ['under', 'over', 'through'] joined with '+' characters (e.g. 'under+over') OR exactly one of ['none'] (e.g. 'none') - A list or array of the above Returns ------- Any|numpy.ndarray """ return self["lineposition"] @lineposition.setter def lineposition(self, val): self["lineposition"] = val @property def linepositionsrc(self): """ Sets the source reference on Chart Studio Cloud for `lineposition`. The 'linepositionsrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["linepositionsrc"] @linepositionsrc.setter def linepositionsrc(self, val): self["linepositionsrc"] = val @property def shadow(self): """ Sets the shape and color of the shadow behind text. "auto" places minimal shadow and applies contrast text font color. See https://developer.mozilla.org/en-US/docs/Web/CSS/text-shadow for additional options. The 'shadow' property is a string and must be specified as: - A string - A number that will be converted to a string - A tuple, list, or one-dimensional numpy array of the above Returns ------- str|numpy.ndarray """ return self["shadow"] @shadow.setter def shadow(self, val): self["shadow"] = val @property def shadowsrc(self): """ Sets the source reference on Chart Studio Cloud for `shadow`. The 'shadowsrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["shadowsrc"] @shadowsrc.setter def shadowsrc(self, val): self["shadowsrc"] = val @property def size(self): """ The 'size' property is a number and may be specified as: - An int or float in the interval [1, inf] - A tuple, list, or one-dimensional numpy array of the above Returns ------- int|float|numpy.ndarray """ return self["size"] @size.setter def size(self, val): self["size"] = val @property def sizesrc(self): """ Sets the source reference on Chart Studio Cloud for `size`. The 'sizesrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["sizesrc"] @sizesrc.setter def sizesrc(self, val): self["sizesrc"] = val @property def style(self): """ Sets whether a font should be styled with a normal or italic face from its family. The 'style' property is an enumeration that may be specified as: - One of the following enumeration values: ['normal', 'italic'] - A tuple, list, or one-dimensional numpy array of the above Returns ------- Any|numpy.ndarray """ return self["style"] @style.setter def style(self, val): self["style"] = val @property def stylesrc(self): """ Sets the source reference on Chart Studio Cloud for `style`. The 'stylesrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["stylesrc"] @stylesrc.setter def stylesrc(self, val): self["stylesrc"] = val @property def textcase(self): """ Sets capitalization of text. It can be used to make text appear in all-uppercase or all-lowercase, or with each word capitalized. The 'textcase' property is an enumeration that may be specified as: - One of the following enumeration values: ['normal', 'word caps', 'upper', 'lower'] - A tuple, list, or one-dimensional numpy array of the above Returns ------- Any|numpy.ndarray """ return self["textcase"] @textcase.setter def textcase(self, val): self["textcase"] = val @property def textcasesrc(self): """ Sets the source reference on Chart Studio Cloud for `textcase`. The 'textcasesrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["textcasesrc"] @textcasesrc.setter def textcasesrc(self, val): self["textcasesrc"] = val @property def variant(self): """ Sets the variant of the font. The 'variant' property is an enumeration that may be specified as: - One of the following enumeration values: ['normal', 'small-caps', 'all-small-caps', 'all-petite-caps', 'petite-caps', 'unicase'] - A tuple, list, or one-dimensional numpy array of the above Returns ------- Any|numpy.ndarray """ return self["variant"] @variant.setter def variant(self, val): self["variant"] = val @property def variantsrc(self): """ Sets the source reference on Chart Studio Cloud for `variant`. The 'variantsrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["variantsrc"] @variantsrc.setter def variantsrc(self, val): self["variantsrc"] = val @property def weight(self): """ Sets the weight (or boldness) of the font. The 'weight' property is a integer and may be specified as: - An int (or float that will be cast to an int) in the interval [1, 1000] OR exactly one of ['normal', 'bold'] (e.g. 'bold') - A tuple, list, or one-dimensional numpy array of the above Returns ------- int|numpy.ndarray """ return self["weight"] @weight.setter def weight(self, val): self["weight"] = val @property def weightsrc(self): """ Sets the source reference on Chart Studio Cloud for `weight`. The 'weightsrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["weightsrc"] @weightsrc.setter def weightsrc(self, val): self["weightsrc"] = val @property def _prop_descriptions(self): return """\ color colorsrc Sets the source reference on Chart Studio Cloud for `color`. family HTML font family - the typeface that will be applied by the web browser. The web browser can only apply a font if it is available on the system where it runs. Provide multiple font families, separated by commas, to indicate the order in which to apply fonts if they aren't available. familysrc Sets the source reference on Chart Studio Cloud for `family`. lineposition Sets the kind of decoration line(s) with text, such as an "under", "over" or "through" as well as combinations e.g. "under+over", etc. linepositionsrc Sets the source reference on Chart Studio Cloud for `lineposition`. shadow Sets the shape and color of the shadow behind text. "auto" places minimal shadow and applies contrast text font color. See https://developer.mozilla.org/en- US/docs/Web/CSS/text-shadow for additional options. shadowsrc Sets the source reference on Chart Studio Cloud for `shadow`. size sizesrc Sets the source reference on Chart Studio Cloud for `size`. style Sets whether a font should be styled with a normal or italic face from its family. stylesrc Sets the source reference on Chart Studio Cloud for `style`. textcase Sets capitalization of text. It can be used to make text appear in all-uppercase or all-lowercase, or with each word capitalized. textcasesrc Sets the source reference on Chart Studio Cloud for `textcase`. variant Sets the variant of the font. variantsrc Sets the source reference on Chart Studio Cloud for `variant`. weight Sets the weight (or boldness) of the font. weightsrc Sets the source reference on Chart Studio Cloud for `weight`. """ def __init__( self, arg=None, color=None, colorsrc=None, family=None, familysrc=None, lineposition=None, linepositionsrc=None, shadow=None, shadowsrc=None, size=None, sizesrc=None, style=None, stylesrc=None, textcase=None, textcasesrc=None, variant=None, variantsrc=None, weight=None, weightsrc=None, **kwargs, ): """ Construct a new Font object Sets the font used in hover labels. Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.sankey.node.hoverlabel.Font` color colorsrc Sets the source reference on Chart Studio Cloud for `color`. family HTML font family - the typeface that will be applied by the web browser. The web browser can only apply a font if it is available on the system where it runs. Provide multiple font families, separated by commas, to indicate the order in which to apply fonts if they aren't available. familysrc Sets the source reference on Chart Studio Cloud for `family`. lineposition Sets the kind of decoration line(s) with text, such as an "under", "over" or "through" as well as combinations e.g. "under+over", etc. linepositionsrc Sets the source reference on Chart Studio Cloud for `lineposition`. shadow Sets the shape and color of the shadow behind text. "auto" places minimal shadow and applies contrast text font color. See https://developer.mozilla.org/en- US/docs/Web/CSS/text-shadow for additional options. shadowsrc Sets the source reference on Chart Studio Cloud for `shadow`. size sizesrc Sets the source reference on Chart Studio Cloud for `size`. style Sets whether a font should be styled with a normal or italic face from its family. stylesrc Sets the source reference on Chart Studio Cloud for `style`. textcase Sets capitalization of text. It can be used to make text appear in all-uppercase or all-lowercase, or with each word capitalized. textcasesrc Sets the source reference on Chart Studio Cloud for `textcase`. variant Sets the variant of the font. variantsrc Sets the source reference on Chart Studio Cloud for `variant`. weight Sets the weight (or boldness) of the font. weightsrc Sets the source reference on Chart Studio Cloud for `weight`. Returns ------- Font """ super().__init__("font") if "_parent" in kwargs: self._parent = kwargs["_parent"] return if arg is None: arg = {} elif isinstance(arg, self.__class__): arg = arg.to_plotly_json() elif isinstance(arg, dict): arg = _copy.copy(arg) else: raise ValueError("""\ The first argument to the plotly.graph_objs.sankey.node.hoverlabel.Font constructor must be a dict or an instance of :class:`plotly.graph_objs.sankey.node.hoverlabel.Font`""") self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) self._set_property("color", arg, color) self._set_property("colorsrc", arg, colorsrc) self._set_property("family", arg, family) self._set_property("familysrc", arg, familysrc) self._set_property("lineposition", arg, lineposition) self._set_property("linepositionsrc", arg, linepositionsrc) self._set_property("shadow", arg, shadow) self._set_property("shadowsrc", arg, shadowsrc) self._set_property("size", arg, size) self._set_property("sizesrc", arg, sizesrc) self._set_property("style", arg, style) self._set_property("stylesrc", arg, stylesrc) self._set_property("textcase", arg, textcase) self._set_property("textcasesrc", arg, textcasesrc) self._set_property("variant", arg, variant) self._set_property("variantsrc", arg, variantsrc) self._set_property("weight", arg, weight) self._set_property("weightsrc", arg, weightsrc) self._process_kwargs(**dict(arg, **kwargs)) self._skip_invalid = False
Font
python
openai__openai-python
src/openai/types/uploads/part_create_params.py
{ "start": 240, "end": 362 }
class ____(TypedDict, total=False): data: Required[FileTypes] """The chunk of bytes for this Part."""
PartCreateParams
python
getsentry__sentry
src/sentry/workflow_engine/processors/delayed_workflow.py
{ "start": 17247, "end": 32158 }
class ____(Exception): """ Raised when a group is missing from a query result. """ def __init__( self, group_id: GroupId, query: UniqueConditionQuery, query_result: QueryResult | None ): self.group_id = group_id self.query = query self.query_result = query_result def _evaluate_group_result_for_dcg( dcg: DataConditionGroup, dcg_to_slow_conditions: dict[DataConditionGroupId, list[DataCondition]], group_id: GroupId, workflow_env: int | None, condition_group_results: dict[UniqueConditionQuery, QueryResult], ) -> bool: slow_conditions = dcg_to_slow_conditions[dcg.id] try: return _group_result_for_dcg( group_id, dcg, workflow_env, condition_group_results, slow_conditions ) except MissingQueryResult as e: # If we didn't get complete query results, don't fire. metrics.incr( "workflow_engine.delayed_workflow.missing_query_result", tags={"got_result": bool(e.query_result)}, sample_rate=1.0, ) logger.warning("workflow_engine.delayed_workflow.missing_query_result", exc_info=True) return False def _group_result_for_dcg( group_id: GroupId, dcg: DataConditionGroup, workflow_env: int | None, condition_group_results: dict[UniqueConditionQuery, QueryResult], slow_conditions: list[DataCondition], ) -> bool: conditions_to_evaluate: list[tuple[DataCondition, list[int | float]]] = [] for condition in slow_conditions: query_values = [] for query in generate_unique_queries(condition, workflow_env): query_result = condition_group_results.get(query) if not query_result or group_id not in query_result: raise MissingQueryResult(group_id, query, query_result) query_values.append(query_result[group_id]) conditions_to_evaluate.append((condition, query_values)) return evaluate_data_conditions( conditions_to_evaluate, DataConditionGroup.Type(dcg.logic_type) ).logic_result.triggered @sentry_sdk.trace def get_groups_to_fire( data_condition_groups: list[DataConditionGroup], workflows_to_envs: Mapping[WorkflowId, int | None], event_data: EventRedisData, condition_group_results: dict[UniqueConditionQuery, QueryResult], dcg_to_slow_conditions: dict[DataConditionGroupId, list[DataCondition]], ) -> dict[GroupId, set[DataConditionGroup]]: data_condition_group_mapping = {dcg.id: dcg for dcg in data_condition_groups} groups_to_fire: dict[GroupId, set[DataConditionGroup]] = defaultdict(set) for event_key in event_data.events: group_id = event_key.group_id if event_key.workflow_id not in workflows_to_envs: # The workflow is deleted, so we can skip it continue workflow_env = workflows_to_envs[event_key.workflow_id] if when_dcg_id := event_key.when_dcg_id: if not ( dcg := data_condition_group_mapping.get(when_dcg_id) ) or not _evaluate_group_result_for_dcg( dcg, dcg_to_slow_conditions, group_id, workflow_env, condition_group_results, ): continue # the WHEN condition passed / was not evaluated, so we can now check the IF conditions for if_dcg_id in event_key.if_dcg_ids: if ( dcg := data_condition_group_mapping.get(if_dcg_id) ) and _evaluate_group_result_for_dcg( dcg, dcg_to_slow_conditions, group_id, workflow_env, condition_group_results, ): groups_to_fire[group_id].add(dcg) for if_dcg_id in event_key.passing_dcg_ids: if dcg := data_condition_group_mapping.get(if_dcg_id): groups_to_fire[group_id].add(dcg) return groups_to_fire @sentry_sdk.trace def bulk_fetch_events(event_ids: list[str], project: Project) -> dict[str, Event]: node_id_to_event_id = { Event.generate_node_id(project.id, event_id=event_id): event_id for event_id in event_ids } node_ids = list(node_id_to_event_id.keys()) fetch_retry_policy = ConditionalRetryPolicy(should_retry_fetch, exponential_delay(1.00)) bulk_data = {} for node_id_chunk in chunked(node_ids, EVENT_LIMIT): with metrics.timer("workflow_engine.process_workflows.fetch_from_nodestore"): bulk_results = fetch_retry_policy(lambda: nodestore.backend.get_multi(node_id_chunk)) bulk_data.update(bulk_results) result: dict[str, Event] = {} for node_id, data in bulk_data.items(): if data is not None: event = Event(event_id=node_id_to_event_id[node_id], project_id=project.id, data=data) # By setting a shared Project, we can ensure that the common pattern of retrieving # the project (and fields thereof) from individual events doesn't duplicate work. event.project = project result[event.event_id] = event return result @metrics.wraps( "workflow_engine.delayed_workflow.get_group_to_groupevent", sample_rate=1.0, ) @sentry_sdk.trace def get_group_to_groupevent( event_data: EventRedisData, groups_to_dcgs: dict[GroupId, set[DataConditionGroup]], project: Project, ) -> dict[Group, tuple[GroupEvent, datetime | None]]: groups = Group.objects.filter(id__in=event_data.group_ids) group_id_to_group = {group.id: group for group in groups} bulk_event_id_to_events = bulk_fetch_events(list(event_data.event_ids), project) bulk_occurrences: list[IssueOccurrence | None] = [] if event_data.occurrence_ids: bulk_occurrences = IssueOccurrence.fetch_multi( list(event_data.occurrence_ids), project_id=project.id ) bulk_occurrence_id_to_occurrence = { occurrence.id: occurrence for occurrence in bulk_occurrences if occurrence } groups_to_dcg_ids = { group_id: {dcg.id for dcg in dcgs} for group_id, dcgs in groups_to_dcgs.items() } group_to_groupevent: dict[Group, tuple[GroupEvent, datetime | None]] = {} for key, instance in event_data.events.items(): if key.dcg_ids.intersection(groups_to_dcg_ids.get(key.group_id, set())): event = bulk_event_id_to_events.get(instance.event_id) group = group_id_to_group.get(key.group_id) if not group or not event: continue group_event = event.for_group(group) if instance.occurrence_id: group_event.occurrence = bulk_occurrence_id_to_occurrence.get( instance.occurrence_id ) group_to_groupevent[group] = (group_event, instance.timestamp) return group_to_groupevent @sentry_sdk.trace def fire_actions_for_groups( organization: Organization, groups_to_fire: dict[GroupId, set[DataConditionGroup]], group_to_groupevent: dict[Group, tuple[GroupEvent, datetime | None]], ) -> None: from sentry.workflow_engine.processors.action import ( filter_recently_fired_workflow_actions, fire_actions, ) serialized_groups = { group.id: group_event.event_id for group, (group_event, _) in group_to_groupevent.items() } logger.info( "workflow_engine.delayed_workflow.fire_actions_for_groups", extra={ "groups_to_fire": groups_to_fire, "group_to_groupevent": serialized_groups, }, ) # Feature check caching to keep us within the trace budget. trigger_actions_ff = features.has("organizations:workflow-engine-trigger-actions", organization) single_processing_ff = features.has( "organizations:workflow-engine-single-process-workflows", organization ) ga_type_ids = options.get("workflow_engine.issue_alert.group.type_id.ga") rollout_type_ids = options.get("workflow_engine.issue_alert.group.type_id.rollout") should_trigger_actions = lambda type_id: ( type_id in ga_type_ids or (type_id in rollout_type_ids and single_processing_ff) or trigger_actions_ff ) total_actions = 0 with track_batch_performance( "workflow_engine.delayed_workflow.fire_actions_for_groups.loop", logger, threshold=timedelta(seconds=40), ) as tracker: for group, (group_event, start_timestamp) in group_to_groupevent.items(): with tracker.track(str(group.id)), log_context.new_context(group_id=group.id): workflow_event_data = WorkflowEventData(event=group_event, group=group) dcgs_for_group = groups_to_fire.get(group.id, set()) filtered_actions = filter_recently_fired_workflow_actions( dcgs_for_group, workflow_event_data ) metrics.incr( "workflow_engine.delayed_workflow.triggered_actions", amount=len(filtered_actions), tags={"event_type": group_event.group.type}, ) workflow_fire_histories = create_workflow_fire_histories( filtered_actions, workflow_event_data, should_trigger_actions(group_event.group.type), is_delayed=True, start_timestamp=start_timestamp, ) event_id = ( workflow_event_data.event.event_id if isinstance(workflow_event_data.event, GroupEvent) else workflow_event_data.event.id ) logger.debug( "workflow_engine.delayed_workflow.triggered_actions", extra={ "workflow_ids": sorted( {wfh.workflow_id for wfh in workflow_fire_histories} ), "actions": [action.id for action in filtered_actions], "event_data": workflow_event_data, "event_id": event_id, }, ) total_actions += len(filtered_actions) fire_actions(filtered_actions, workflow_event_data) logger.debug( "workflow_engine.delayed_workflow.triggered_actions_summary", extra={"total_actions": total_actions}, ) @sentry_sdk.trace def cleanup_redis_buffer( client: ProjectDelayedWorkflowClient, event_keys: Iterable[EventKey], batch_key: str | None ) -> None: client.delete_hash_fields(batch_key=batch_key, fields=[key.original_key for key in event_keys]) def repr_keys[T, V](d: dict[T, V]) -> dict[str, V]: return {repr(key): value for key, value in d.items()} def _summarize_by_first[T1, T2: int | str](it: Iterable[tuple[T1, T2]]) -> dict[T1, list[T2]]: "Logging helper to allow pairs to be summarized as a mapping from first to list of second" result = defaultdict(set) for key, value in it: result[key].add(value) return {key: sorted(values) for key, values in result.items()} @sentry_sdk.trace def process_delayed_workflows( batch_client: DelayedWorkflowClient, project_id: int, batch_key: str | None = None ) -> None: """ Grab workflows, groups, and data condition groups from the Redis buffer, evaluate the "slow" conditions in a bulk snuba query, and fire them if they pass """ with sentry_sdk.start_span(op="delayed_workflow.prepare_data"): project = fetch_project(project_id) if not project: return if features.has( "organizations:workflow-engine-process-workflows-logs", project.organization ): log_context.set_verbose(True) redis_data = batch_client.for_project(project_id).get_hash_data(batch_key) event_data = EventRedisData.from_redis_data(redis_data, continue_on_error=True) metrics.incr( "workflow_engine.delayed_workflow", amount=len(event_data.events), ) workflows_to_envs = fetch_workflows_envs(list(event_data.workflow_ids)) data_condition_groups = fetch_data_condition_groups(list(event_data.dcg_ids)) dcg_to_slow_conditions = get_slow_conditions_for_groups(list(event_data.dcg_ids)) # Ensure we have a record of the involved workflows in our logs. logger.debug( "delayed_workflow.workflows", extra={ "workflows": sorted(event_data.workflow_ids), }, ) # Ensure we log which groups/events being processed by which workflows. # This is logged independently to avoid the risk of generating log messages that need to be # truncated (and thus no longer valid JSON that we can query). logger.debug( "delayed_workflow.group_events_to_workflow_ids", extra={ "group_events_to_workflow_ids": _summarize_by_first( (f"{event_key.group_id}:{instance.event_id}", event_key.workflow_id) for event_key, instance in event_data.events.items() ), }, ) # Get unique query groups to query Snuba condition_groups = get_condition_query_groups( data_condition_groups, event_data, workflows_to_envs, dcg_to_slow_conditions ) if not condition_groups: return logger.debug( "delayed_workflow.condition_query_groups", extra={ "condition_groups": repr_keys(condition_groups), "num_condition_groups": len(condition_groups), }, ) try: condition_group_results = get_condition_group_results(condition_groups) except SnubaError: # We expect occasional errors, so we report as info and retry. sentry_sdk.capture_exception(level="info") retry_task() logger.debug( "delayed_workflow.condition_group_results", extra={ "condition_group_results": repr_keys(condition_group_results), }, ) # Evaluate DCGs groups_to_dcgs = get_groups_to_fire( data_condition_groups, workflows_to_envs, event_data, condition_group_results, dcg_to_slow_conditions, ) logger.debug( "delayed_workflow.groups_to_fire", extra={ "groups_to_dcgs": { group_id: sorted(dcg.id for dcg in dcgs) for group_id, dcgs in groups_to_dcgs.items() }, }, ) group_to_groupevent = get_group_to_groupevent( event_data, groups_to_dcgs, project, ) fire_actions_for_groups(project.organization, groups_to_dcgs, group_to_groupevent) cleanup_redis_buffer(batch_client.for_project(project_id), event_data.events.keys(), batch_key)
MissingQueryResult
python
huggingface__transformers
src/transformers/models/metaclip_2/modeling_metaclip_2.py
{ "start": 29895, "end": 39079 }
class ____(MetaClip2PreTrainedModel): """ 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 ([`MetaClip2Config`]): 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, MetaClip2Model >>> model = MetaClip2Model.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( ... text=["a photo of a cat", "a photo of a dog"], images=image, return_tensors="pt", padding=True ... ) >>> outputs = model(**inputs) >>> logits_per_image = outputs.logits_per_image # this is the image-text similarity score >>> probs = logits_per_image.softmax(dim=1) # we can take the softmax to get the label probabilities ```""" config: MetaClip2Config _no_split_modules = ["MetaClip2TextEmbeddings", "MetaClip2EncoderLayer", "MetaClip2VisionEmbeddings"] def __init__(self, config: MetaClip2Config): super().__init__(config) if not isinstance(config.text_config, MetaClip2TextConfig): raise TypeError( "config.text_config is expected to be of type MetaClip2TextConfig but is of type" f" {type(config.text_config)}." ) if not isinstance(config.vision_config, MetaClip2VisionConfig): raise TypeError( "config.vision_config is expected to be of type MetaClip2VisionConfig but is of type" f" {type(config.vision_config)}." ) text_config = config.text_config vision_config = config.vision_config self.projection_dim = config.projection_dim self.text_embed_dim = text_config.hidden_size self.vision_embed_dim = vision_config.hidden_size text_model = MetaClip2TextModel._from_config(text_config) self.text_model = text_model.text_model vision_model = MetaClip2VisionModel._from_config(vision_config) self.vision_model = vision_model.vision_model self.visual_projection = nn.Linear(self.vision_embed_dim, self.projection_dim, bias=False) self.text_projection = nn.Linear(self.text_embed_dim, self.projection_dim, bias=False) self.logit_scale = nn.Parameter(torch.tensor(self.config.logit_scale_init_value)) # Initialize weights and apply final processing self.post_init() @filter_out_non_signature_kwargs() @auto_docstring def get_text_features( self, input_ids: Optional[torch.Tensor] = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.Tensor] = None, ) -> torch.FloatTensor: r""" Returns: text_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The text embeddings obtained by applying the projection layer to the pooled output of [`MetaClip2TextModel`]. Examples: ```python >>> from transformers import AutoTokenizer, MetaClip2Model >>> model = MetaClip2Model.from_pretrained("facebook/metaclip-2-worldwide-huge-quickgelu") >>> tokenizer = AutoTokenizer.from_pretrained("facebook/metaclip-2-worldwide-huge-quickgelu") >>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt") >>> text_features = model.get_text_features(**inputs) ```""" text_outputs: BaseModelOutputWithPooling = self.text_model( input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids, ) pooled_output = text_outputs.pooler_output text_features = self.text_projection(pooled_output) return text_features @filter_out_non_signature_kwargs() @auto_docstring def get_image_features( self, pixel_values: Optional[torch.FloatTensor] = None, interpolate_pos_encoding: bool = False, ) -> torch.FloatTensor: r""" Returns: image_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The image embeddings obtained by applying the projection layer to the pooled output of [`MetaClip2VisionModel`]. Examples: ```python >>> from PIL import Image >>> import requests >>> from transformers import AutoProcessor, MetaClip2Model >>> model = MetaClip2Model.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") >>> image_features = model.get_image_features(**inputs) ```""" vision_outputs: BaseModelOutputWithPooling = self.vision_model( pixel_values=pixel_values, interpolate_pos_encoding=interpolate_pos_encoding, ) pooled_output = vision_outputs.pooler_output image_features = self.visual_projection(pooled_output) return image_features @can_return_tuple @auto_docstring def forward( self, input_ids: Optional[torch.LongTensor] = None, pixel_values: Optional[torch.FloatTensor] = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, return_loss: Optional[bool] = None, interpolate_pos_encoding: bool = False, **kwargs: Unpack[TransformersKwargs], ) -> MetaClip2Output: r""" return_loss (`bool`, *optional*): Whether or not to return the contrastive loss. Examples: ```python >>> from PIL import Image >>> import requests >>> from transformers import AutoProcessor, MetaClip2Model >>> model = MetaClip2Model.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( ... text=["a photo of a cat", "a photo of a dog"], images=image, return_tensors="pt", padding=True ... ) >>> outputs = model(**inputs) >>> logits_per_image = outputs.logits_per_image # this is the image-text similarity score >>> probs = logits_per_image.softmax(dim=1) # we can take the softmax to get the label probabilities ```""" vision_outputs: BaseModelOutputWithPooling = self.vision_model( pixel_values=pixel_values, interpolate_pos_encoding=interpolate_pos_encoding, **kwargs, ) text_outputs: BaseModelOutputWithPooling = self.text_model( input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids, **kwargs, ) image_embeds = vision_outputs.pooler_output image_embeds = self.visual_projection(image_embeds) text_embeds = text_outputs.pooler_output text_embeds = self.text_projection(text_embeds) # normalized features image_embeds = image_embeds / _get_vector_norm(image_embeds) text_embeds = text_embeds / _get_vector_norm(text_embeds) # cosine similarity as logits logits_per_text = torch.matmul(text_embeds, image_embeds.t().to(text_embeds.device)) logits_per_text = logits_per_text * self.logit_scale.exp().to(text_embeds.device) logits_per_image = logits_per_text.t() loss = None if return_loss: loss = metaclip_2_loss(logits_per_text) return MetaClip2Output( loss=loss, logits_per_image=logits_per_image, logits_per_text=logits_per_text, text_embeds=text_embeds, image_embeds=image_embeds, text_model_output=text_outputs, vision_model_output=vision_outputs, )
MetaClip2Model
python
matplotlib__matplotlib
lib/matplotlib/backends/backend_macosx.py
{ "start": 4359, "end": 5750 }
class ____(_macosx.NavigationToolbar2, NavigationToolbar2): def __init__(self, canvas): data_path = cbook._get_data_path('images') _, tooltips, image_names, _ = zip(*NavigationToolbar2.toolitems) _macosx.NavigationToolbar2.__init__( self, canvas, tuple(str(data_path / image_name) + ".pdf" for image_name in image_names if image_name is not None), tuple(tooltip for tooltip in tooltips if tooltip is not None)) NavigationToolbar2.__init__(self, canvas) def draw_rubberband(self, event, x0, y0, x1, y1): self.canvas.set_rubberband(int(x0), int(y0), int(x1), int(y1)) def remove_rubberband(self): self.canvas.remove_rubberband() def save_figure(self, *args): directory = os.path.expanduser(mpl.rcParams['savefig.directory']) filename = _macosx.choose_save_file('Save the figure', directory, self.canvas.get_default_filename()) if filename is None: # Cancel return # Save dir for next time, unless empty str (which means use cwd). if mpl.rcParams['savefig.directory']: mpl.rcParams['savefig.directory'] = os.path.dirname(filename) self.canvas.figure.savefig(filename) return filename
NavigationToolbar2Mac
python
pytorch__pytorch
torch/_dynamo/variables/iter.py
{ "start": 18109, "end": 19199 }
class ____(ZipVariable): """ Represents map(fn, *iterables) """ def __init__( self, fn: VariableTracker, iterables: list[VariableTracker], **kwargs: Any, ) -> None: super().__init__(iterables, **kwargs) self.fn = fn def python_type(self) -> type: return map def has_unpack_var_sequence(self, tx: "InstructionTranslator") -> bool: return False def next_variable(self, tx: "InstructionTranslator") -> VariableTracker: args = super().next_variable(tx) return self.fn.call_function(tx, args.items, {}) # type: ignore[attr-defined] def reconstruct(self, codegen: "PyCodegen") -> None: codegen.add_push_null( lambda: codegen.load_import_from("builtins", "map"), call_function_ex=True ) codegen(self.fn) self.reconstruct_items(codegen) codegen.extend_output( [ create_build_tuple(len(self.iterables) + 1), *create_call_function_ex(False, False), ] )
MapVariable
python
getsentry__sentry
tests/sentry/integrations/msteams/notifications/test_note.py
{ "start": 590, "end": 2232 }
class ____(MSTeamsActivityNotificationTest): def test_note(self, mock_send_card: MagicMock) -> None: """ Test that the card for MS Teams notification is generated correctly when a comment is made on an issue. """ notification = NoteActivityNotification( Activity( project=self.project, group=self.group, user_id=self.user.id, type=ActivityType.NOTE, data={"text": "text", "mentions": []}, ) ) with self.tasks(): notification.send() mock_send_card.assert_called_once() args, kwargs = mock_send_card.call_args assert args[0] == "some_conversation_id" body = args[1]["body"] assert 4 == len(body) assert f"New comment by {self.user.get_display_name()}" == body[0]["text"] assert ( f"[{self.group.title}](http://testserver/organizations/{self.organization.slug}/issues/{self.group.id}/?referrer=note\\_activity-msteams&amp;notification\\_uuid=" in body[1]["text"] ) assert notification.activity.data["text"] == body[2]["text"] notification_uuid = self.get_notification_uuid(body[3]["columns"][1]["items"][0]["text"]) assert ( f"{self.project.slug} | [Notification Settings](http://testserver/settings/account/notifications/workflow/?referrer=note\\_activity-msteams-user&amp;notification\\_uuid={notification_uuid}&amp;organizationId={self.organization.id})" == body[3]["columns"][1]["items"][0]["text"] )
MSTeamsNoteNotificationTest
python
redis__redis-py
tests/test_asyncio/test_multidb/test_pipeline.py
{ "start": 10371, "end": 19684 }
class ____: @pytest.mark.asyncio @pytest.mark.parametrize( "mock_multi_db_config,mock_db, mock_db1, mock_db2", [ ( {}, {"weight": 0.2, "circuit": {"state": CBState.CLOSED}}, {"weight": 0.7, "circuit": {"state": CBState.CLOSED}}, {"weight": 0.5, "circuit": {"state": CBState.CLOSED}}, ), ], indirect=True, ) async def test_executes_transaction_against_correct_db( self, mock_multi_db_config, mock_db, mock_db1, mock_db2, mock_hc ): databases = create_weighted_list(mock_db, mock_db1, mock_db2) with ( patch.object(mock_multi_db_config, "databases", return_value=databases), patch.object( mock_multi_db_config, "default_health_checks", return_value=[mock_hc] ), ): mock_db1.client.transaction.return_value = ["OK1", "value1"] mock_hc.check_health.return_value = True async with MultiDBClient(mock_multi_db_config) as client: assert ( mock_multi_db_config.failover_strategy.set_databases.call_count == 1 ) async def callback(pipe: Pipeline): pipe.set("key1", "value1") pipe.get("key1") assert await client.transaction(callback) == ["OK1", "value1"] # if we assume at least 3 health checks have run per each database # we should have at least 9 total calls assert len(mock_hc.check_health.call_args_list) >= 9 @pytest.mark.asyncio @pytest.mark.parametrize( "mock_multi_db_config,mock_db, mock_db1, mock_db2", [ ( {}, {"weight": 0.2, "circuit": {"state": CBState.CLOSED}}, {"weight": 0.5, "circuit": {"state": CBState.CLOSED}}, {"weight": 0.7, "circuit": {"state": CBState.OPEN}}, ), ], indirect=True, ) async def test_execute_transaction_against_correct_db_and_closed_circuit( self, mock_multi_db_config, mock_db, mock_db1, mock_db2, mock_hc ): databases = create_weighted_list(mock_db, mock_db1, mock_db2) with ( patch.object(mock_multi_db_config, "databases", return_value=databases), patch.object( mock_multi_db_config, "default_health_checks", return_value=[mock_hc] ), ): mock_db1.client.transaction.return_value = ["OK1", "value1"] async def mock_check_health(database): if database == mock_db2: return False else: return True mock_hc.check_health.side_effect = mock_check_health async with MultiDBClient(mock_multi_db_config) as client: assert ( mock_multi_db_config.failover_strategy.set_databases.call_count == 1 ) async def callback(pipe: Pipeline): pipe.set("key1", "value1") pipe.get("key1") assert await client.transaction(callback) == ["OK1", "value1"] assert len(mock_hc.check_health.call_args_list) >= 7 assert mock_db.circuit.state == CBState.CLOSED assert mock_db1.circuit.state == CBState.CLOSED assert mock_db2.circuit.state == CBState.OPEN @pytest.mark.asyncio @pytest.mark.parametrize( "mock_multi_db_config,mock_db, mock_db1, mock_db2", [ ( {"health_check_probes": 1}, {"weight": 0.2, "circuit": {"state": CBState.CLOSED}}, {"weight": 0.7, "circuit": {"state": CBState.CLOSED}}, {"weight": 0.5, "circuit": {"state": CBState.CLOSED}}, ), ], indirect=True, ) async def test_execute_transaction_against_correct_db_on_background_health_check_determine_active_db_unhealthy( self, mock_multi_db_config, mock_db, mock_db1, mock_db2, mock_hc ): cb = PBCircuitBreakerAdapter(pybreaker.CircuitBreaker(reset_timeout=5)) cb.database = mock_db mock_db.circuit = cb cb1 = PBCircuitBreakerAdapter(pybreaker.CircuitBreaker(reset_timeout=5)) cb1.database = mock_db1 mock_db1.circuit = cb1 cb2 = PBCircuitBreakerAdapter(pybreaker.CircuitBreaker(reset_timeout=5)) cb2.database = mock_db2 mock_db2.circuit = cb2 databases = create_weighted_list(mock_db, mock_db1, mock_db2) # Track health check runs across all databases health_check_run = 0 # Create events for each failover scenario db1_became_unhealthy = asyncio.Event() db2_became_unhealthy = asyncio.Event() db_became_unhealthy = asyncio.Event() counter_lock = asyncio.Lock() async def mock_check_health(database): nonlocal health_check_run # Increment run counter for each health check call async with counter_lock: health_check_run += 1 current_run = health_check_run # Run 1 (health_check_run 1-3): All databases healthy if current_run <= 3: return True # Run 2 (health_check_run 4-6): mock_db1 unhealthy, others healthy elif current_run <= 6: if database == mock_db1: if current_run == 6: db1_became_unhealthy.set() return False # Signal that db1 has become unhealthy after all 3 checks if current_run == 6: db1_became_unhealthy.set() return True # Run 3 (health_check_run 7-9): mock_db1 and mock_db2 unhealthy, mock_db healthy elif current_run <= 9: if database == mock_db1 or database == mock_db2: if current_run == 9: db2_became_unhealthy.set() return False # Signal that db2 has become unhealthy after all 3 checks if current_run == 9: db2_became_unhealthy.set() return True # Run 4 (health_check_run 10-12): mock_db unhealthy, others healthy else: if database == mock_db: if current_run >= 12: db_became_unhealthy.set() return False # Signal that db has become unhealthy after all 3 checks if current_run >= 12: db_became_unhealthy.set() return True mock_hc.check_health.side_effect = mock_check_health with ( patch.object(mock_multi_db_config, "databases", return_value=databases), patch.object( mock_multi_db_config, "default_health_checks", return_value=[mock_hc], ), ): mock_db.client.transaction.return_value = ["OK", "value"] mock_db1.client.transaction.return_value = ["OK1", "value"] mock_db2.client.transaction.return_value = ["OK2", "value"] mock_multi_db_config.health_check_interval = 0.1 mock_multi_db_config.failover_strategy = WeightBasedFailoverStrategy() async with MultiDBClient(mock_multi_db_config) as client: async def callback(pipe: Pipeline): pipe.set("key1", "value1") pipe.get("key1") assert await client.transaction(callback) == ["OK1", "value"] # Wait for mock_db1 to become unhealthy assert await db1_became_unhealthy.wait(), ( "Timeout waiting for mock_db1 to become unhealthy" ) await wait_for_condition( lambda: cb1.state == CBState.OPEN, timeout=0.2, error_message="Timeout waiting for cb1 to open", ) assert await client.transaction(callback) == ["OK2", "value"] # Wait for mock_db2 to become unhealthy assert await db2_became_unhealthy.wait(), ( "Timeout waiting for mock_db1 to become unhealthy" ) await wait_for_condition( lambda: cb2.state == CBState.OPEN, timeout=0.2, error_message="Timeout waiting for cb2 to open", ) assert await client.transaction(callback) == ["OK", "value"] # Wait for mock_db to become unhealthy assert await db_became_unhealthy.wait(), ( "Timeout waiting for mock_db1 to become unhealthy" ) await wait_for_condition( lambda: cb.state == CBState.OPEN, timeout=0.2, error_message="Timeout waiting for cb to open", ) assert await client.transaction(callback) == ["OK1", "value"]
TestTransaction
python
readthedocs__readthedocs.org
readthedocs/api/v3/filters.py
{ "start": 1804, "end": 1963 }
class ____(filters.FilterSet): class Meta: model = Notification fields = { "state": ["in", "exact"], }
NotificationFilter
python
tensorflow__tensorflow
tensorflow/python/compiler/tensorrt/test/reshape_transpose_test.py
{ "start": 1063, "end": 3497 }
class ____(trt_test.TfTrtIntegrationTestBase): def GraphFn(self, inp): outputs = [] # Here we test two types of reshapes, one changes the batch dimension and # the other does not. Note that we're not able to test reshaping to # scalar, since TRT requires input tensor to be of rank at least 2, so a # reshape with scalar input will be filtered out of the segment before # conversion. # # These reshapes happen at batch dimension, thus conversion should fail. orig_shape = constant_op.constant([-1, 24, 24, 2], name="original_shape") for shape in [[2, 50, 24, 24, 2], [-1, 50, 24, 24, 2], [2, 50, -1, 24, 2]]: incompatible_reshape = array_ops.reshape(inp, shape) reshape_back = array_ops.reshape(incompatible_reshape, orig_shape) outputs.append(self.trt_incompatible_op(reshape_back)) # Add another block with many reshapes that don't change the batch # dimension. compatible_reshape = array_ops.reshape( inp, [-1, 24 * 24, 2], name="reshape-0") compatible_reshape = array_ops.reshape( compatible_reshape, [100, 24, -1], name="reshape-1") compatible_reshape = array_ops.reshape( compatible_reshape, [100, 24 * 2, 24], name="reshape-2") compatible_reshape = array_ops.reshape( compatible_reshape, [-1, 24, 24 * 2], name="reshape-3") compatible_reshape = array_ops.reshape( compatible_reshape, [-1, 6, 4, 24, 2], name="reshape-4") compatible_reshape = array_ops.reshape( compatible_reshape, [-1, 6, 4, 6, 4, 2, 1], name="reshape-5") compatible_reshape = array_ops.reshape( compatible_reshape, [-1, 24, 24, 2], name="reshape-6") outputs.append(self.trt_incompatible_op(compatible_reshape)) return math_ops.add_n(outputs, name="output_0") def GetParams(self): return self.BuildParams(self.GraphFn, dtypes.float32, [[100, 24, 24, 2]], [[100, 24, 24, 2]]) def ExpectedEnginesToBuild(self, run_params): """Return the expected engines to build.""" return { "TRTEngineOp_000": ["reshape-%d" % i for i in range(7)] + ["reshape-%d/shape" % i for i in range(7)] } def ShouldRunTest(self, run_params): """Whether to run the test.""" return (not trt_test.IsQuantizationMode(run_params.precision_mode) and not run_params.dynamic_engine), "test static engine and non-INT8"
ReshapeTest
python
pytorch__pytorch
torch/_dynamo/functional_export.py
{ "start": 8339, "end": 18562 }
class ____(torch.fx.Transformer): """Graph transformer for dynamo export that flattens inputs/outputs without complex matching.""" def __init__( self, module: torch.fx.GraphModule, flat_inputs: list[Any], flat_args_dynamic_dims: list[set[int]], graph_input_order: dict[int, int], graph_output_map: dict[int, tuple[str, Any]], fake_mode: Optional[Any] = None, ) -> None: super().__init__(module) assert len(flat_args_dynamic_dims) == len(flat_inputs) self.flat_inputs = flat_inputs self.flat_args_dynamic_dims = flat_args_dynamic_dims self.graph_input_order = graph_input_order self.graph_output_map = graph_output_map self.fake_mode = fake_mode # Get original placeholders and output self.placeholders = [n for n in module.graph.nodes if n.op == "placeholder"] self.output_node = next(n for n in module.graph.nodes if n.op == "output") # Create new flattened input placeholders self.new_input_nodes: dict[int, torch.fx.Node] = {} self._create_flattened_inputs() # Iterator for replacing old placeholders self.old_to_new_mapping = {} self._create_placeholder_mapping() def _create_flattened_inputs(self) -> None: """Create new placeholder nodes for flattened inputs with proper fake tensors.""" for i in range(len(self.flat_inputs)): placeholder = super().placeholder(f"arg_{i}", (), {}) # Check if this user input (index i) maps to a graph placeholder if i in self.graph_input_order: # graph_input_order[i] gives us which graph placeholder this user input corresponds to graph_placeholder_idx = self.graph_input_order[i] if graph_placeholder_idx < len(self.placeholders): orig_placeholder = self.placeholders[graph_placeholder_idx] # Copy other metadata but not "val" yet for key, value in orig_placeholder.meta.items(): if key != "val": placeholder.node.meta[key] = value # Always ensure we have proper "val" metadata from fake tensor if self.fake_mode is not None and isinstance( self.flat_inputs[i], torch.Tensor ): placeholder.node.meta["val"] = self.fake_mode.from_tensor( self.flat_inputs[i], symbolic_context=StatelessSymbolicContext( dynamic_sizes=[ ( DimDynamic.DYNAMIC if d in self.flat_args_dynamic_dims[i] else DimDynamic.STATIC ) for d in range(len(self.flat_inputs[i].shape)) ], constraint_sizes=[None] * len(self.flat_inputs[i].shape), ), ) elif hasattr(self.flat_inputs[i], "val"): # _IntWrapper case placeholder.node.meta["val"] = self.flat_inputs[i].val else: placeholder.node.meta["val"] = self.flat_inputs[i] # pyrefly: ignore [unsupported-operation] self.new_input_nodes[i] = placeholder def _create_placeholder_mapping(self) -> None: """Create mapping from old placeholders to new ones.""" # graph_input_order maps: user_input_index -> graph_placeholder_index # We need to create: old_graph_placeholder -> new_user_input_placeholder for user_input_idx, graph_placeholder_idx in self.graph_input_order.items(): if graph_placeholder_idx < len(self.placeholders): old_placeholder = self.placeholders[graph_placeholder_idx] new_placeholder = self.new_input_nodes[user_input_idx] self.old_to_new_mapping[old_placeholder] = new_placeholder def placeholder(self, target, args, kwargs) -> Any: """Replace old placeholders with new flattened ones.""" # Return the corresponding new placeholder if self.current_node in self.old_to_new_mapping: new_arg = self.old_to_new_mapping[self.current_node] # Copy over additional metadata from current node, but don't overwrite "val" for key in ["tensor_dict", "example_value", "unbacked_bindings"]: if key in self.current_node.meta: new_arg.node.meta[key] = self.current_node.meta[key] # Only copy "val" if we don't already have a good one if "val" in self.current_node.meta and "val" not in new_arg.node.meta: new_arg.node.meta["val"] = self.current_node.meta["val"] return new_arg else: # Shouldn't happen if mapping is correct, but fallback return super().placeholder(target, args, kwargs) def output(self, target, args, kwargs) -> Any: """Transform output according to graph_output_map.""" original_outputs = args[0] # Build new output list based on graph_output_map new_outputs = [] for i in sorted(self.graph_output_map.keys()): output_type, val = self.graph_output_map[i] if output_type == "graph_out": new_outputs.append(original_outputs[val]) elif output_type == "input": input_idx = val.index new_outputs.append(self.new_input_nodes[input_idx]) elif output_type == "constant": new_outputs.append(val) return super().output(target, (tuple(new_outputs),), {}) def run_node(self, node: Node) -> Any: """Run node transformation and preserve metadata.""" self.current_node = node result = super().run_node(node) # Copy important metadata if hasattr(result, "node") and result.node is not node: for key in ["val", "example_value", "unbacked_bindings"]: if key in node.meta: result.node.meta[key] = node.meta[key] # Preserve node names (except output) if node.op != "output" and hasattr(node, "name"): result.node._rename(node.name) return result def transform(self) -> torch.fx.GraphModule: """Perform the graph transformation and copy module metadata.""" result_gm = super().transform() # Copy module metadata like the original implementation if hasattr(self.module, "meta"): # pyrefly: ignore [unsupported-operation] if "dynamo_flat_name_to_original_fqn" in self.module.meta: # pyrefly: ignore [index-error] result_gm.meta["dynamo_flat_name_to_original_fqn"] = self.module.meta[ # pyrefly: ignore [index-error] "dynamo_flat_name_to_original_fqn" ] # pyrefly: ignore [unsupported-operation] if "dynamo_compile_id" in self.module.meta: # pyrefly: ignore [index-error] result_gm.meta["dynamo_compile_id"] = self.module.meta[ # pyrefly: ignore [index-error] "dynamo_compile_id" ] return result_gm def _suggest_or_raise_constraint_violation( module_to_trace: torch.nn.Module, orig_callable: Callable, # type: ignore[type-arg] fake_mode: Optional["FakeTensorMode"], graph_capture_output: CaptureOutput, args: Any, kwargs: Any, dynamic_shapes: Optional[Union[dict[str, Any], tuple[Any], list[Any]]], ): constraint_violation_error = None try: # Check if we have any constraint violations fn, _ = get_traced_fn(module_to_trace) graph_capture_output.graph_capture_output.build_guards(fn.__code__) except ConstraintViolationError as e: constraint_violation_error = e if ( (shape_env := getattr(fake_mode, "shape_env", None)) is not None and (dim_constraints := shape_env.dim_constraints) is not None and not isinstance( module_to_trace.forward, torch._ops.OpOverloadPacket | torch._ops.OpOverload, ) ): dim_constraints.solve() forced_specializations = dim_constraints.forced_specializations() msg = dim_constraints.prettify_results( inspect.signature(orig_callable), # type: ignore[attr-defined] dynamic_shapes, constraint_violation_error, forced_specializations, ) if constraint_violation_error: constraint_violation_error.args = ( constraint_violation_error.args[0] + msg, ) else: if forced_specializations: constraint_violation_error = ConstraintViolationError(msg) else: log.info( "Summary of dimension constraints:%s", msg, ) # Error if we have any constraints on static values for k in shape_env.var_to_range: if isinstance(k, sympy.Integer): constraint_violation_error = ConstraintViolationError( f"{''.join(traceback.format_list(shape_env.var_to_stack[k]))}\n" "It appears that you're trying to set a constraint on a " f"value which we evaluated to have a static value of {k}. " 'Set TORCH_LOGS="+export" for more information.' ) if constraint_violation_error: constraint_violation_error = post_process_error_msg( constraint_violation_error, orig_callable, args, kwargs ) raise constraint_violation_error def _normalize_shuffle_graph(shuffle_gm: torch.fx.GraphModule) -> None: shuffle_gm.graph.eliminate_dead_code() shuffle_gm.recompile() for name, buffer in list(shuffle_gm.named_buffers()): delattr(shuffle_gm, name) setattr(shuffle_gm, name, buffer) @dataclass(frozen=True)
DynamoGraphTransformer
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 775114, "end": 775897 }
class ____(sgqlc.types.Type, Node): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ( "actor", "after_commit", "before_commit", "created_at", "pull_request", "ref", ) actor = sgqlc.types.Field(Actor, graphql_name="actor") after_commit = sgqlc.types.Field(Commit, graphql_name="afterCommit") before_commit = sgqlc.types.Field(Commit, graphql_name="beforeCommit") created_at = sgqlc.types.Field( sgqlc.types.non_null(DateTime), graphql_name="createdAt" ) pull_request = sgqlc.types.Field( sgqlc.types.non_null("PullRequest"), graphql_name="pullRequest" ) ref = sgqlc.types.Field("Ref", graphql_name="ref")
HeadRefForcePushedEvent
python
jmcnamara__XlsxWriter
xlsxwriter/test/worksheet/test_write_sheet_views5.py
{ "start": 301, "end": 3686 }
class ____(unittest.TestCase): """ Test the Worksheet _write_sheet_views() method. """ def setUp(self): self.fh = StringIO() self.worksheet = Worksheet() self.worksheet._set_filehandle(self.fh) def test_write_sheet_views1(self): """Test the _write_sheet_views() method with selection set""" self.worksheet.select() self.worksheet.set_selection("A1") self.worksheet._write_sheet_views() exp = '<sheetViews><sheetView tabSelected="1" workbookViewId="0"/></sheetViews>' got = self.fh.getvalue() self.assertEqual(exp, got) def test_write_sheet_views2(self): """Test the _write_sheet_views() method with selection set""" self.worksheet.select() self.worksheet.set_selection("A2") self.worksheet._write_sheet_views() exp = '<sheetViews><sheetView tabSelected="1" workbookViewId="0"><selection activeCell="A2" sqref="A2"/></sheetView></sheetViews>' got = self.fh.getvalue() self.assertEqual(exp, got) def test_write_sheet_views3(self): """Test the _write_sheet_views() method with selection set""" self.worksheet.select() self.worksheet.set_selection("B1") self.worksheet._write_sheet_views() exp = '<sheetViews><sheetView tabSelected="1" workbookViewId="0"><selection activeCell="B1" sqref="B1"/></sheetView></sheetViews>' got = self.fh.getvalue() self.assertEqual(exp, got) def test_write_sheet_views4(self): """Test the _write_sheet_views() method with selection set""" self.worksheet.select() self.worksheet.set_selection("D3") self.worksheet._write_sheet_views() exp = '<sheetViews><sheetView tabSelected="1" workbookViewId="0"><selection activeCell="D3" sqref="D3"/></sheetView></sheetViews>' got = self.fh.getvalue() self.assertEqual(exp, got) def test_write_sheet_views5(self): """Test the _write_sheet_views() method with selection set""" self.worksheet.select() self.worksheet.set_selection("D3:F4") self.worksheet._write_sheet_views() exp = '<sheetViews><sheetView tabSelected="1" workbookViewId="0"><selection activeCell="D3" sqref="D3:F4"/></sheetView></sheetViews>' got = self.fh.getvalue() self.assertEqual(exp, got) def test_write_sheet_views6(self): """Test the _write_sheet_views() method with selection set""" self.worksheet.select() # With reversed selection direction. self.worksheet.set_selection("F4:D3") self.worksheet._write_sheet_views() exp = '<sheetViews><sheetView tabSelected="1" workbookViewId="0"><selection activeCell="F4" sqref="D3:F4"/></sheetView></sheetViews>' got = self.fh.getvalue() self.assertEqual(exp, got) def test_write_sheet_views7(self): """Test the _write_sheet_views() method with selection set""" self.worksheet.select() # Should be the same as 'A2' self.worksheet.set_selection("A2:A2") self.worksheet._write_sheet_views() exp = '<sheetViews><sheetView tabSelected="1" workbookViewId="0"><selection activeCell="A2" sqref="A2"/></sheetView></sheetViews>' got = self.fh.getvalue() self.assertEqual(exp, got)
TestWriteSheetViews
python
pandas-dev__pandas
asv_bench/benchmarks/series_methods.py
{ "start": 1731, "end": 2982 }
class ____: params = [ [ "datetime64[ns]", "float32", "float64", "Float64", "Int64", "int64[pyarrow]", "string", "string[pyarrow]", ], ] param_names = ["dtype"] def setup(self, dtype): N = 10**6 if dtype == "datetime64[ns]": data = date_range("2000-01-01", freq="s", periods=N) na_value = NaT elif dtype in ("float64", "Float64"): data = np.random.randn(N) na_value = np.nan elif dtype in ("Int64", "int64[pyarrow]"): data = np.arange(N) na_value = NA elif dtype in ("string", "string[pyarrow]"): data = np.array([str(i) * 5 for i in range(N)], dtype=object) na_value = NA else: raise NotImplementedError fill_value = data[0] ser = Series(data, dtype=dtype) ser[::2] = na_value self.ser = ser self.fill_value = fill_value def time_fillna(self, dtype): self.ser.fillna(value=self.fill_value) def time_ffill(self, dtype): self.ser.ffill() def time_bfill(self, dtype): self.ser.bfill()
Fillna
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chart_format30.py
{ "start": 315, "end": 1786 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chart_format30.xlsx") def test_create_file(self): """Test the creation of an XlsxWriter file with chart formatting.""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() chart = workbook.add_chart({"type": "line"}) chart.axis_ids = [108652416, 108655744] 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", "trendline": { "type": "linear", "intercept": 0.8, "display_equation": True, "display_r_squared": True, }, } ) chart.add_series( { "categories": "=Sheet1!$A$1:$A$5", "values": "=Sheet1!$C$1:$C$5", } ) chart.set_legend({"delete_series": [0, 2]}) worksheet.insert_chart("E9", chart) workbook.close() self.assertExcelEqual()
TestCompareXLSXFiles
python
great-expectations__great_expectations
contrib/experimental/great_expectations_experimental/expectations/expect_queried_column_values_to_exist_in_second_table_column.py
{ "start": 272, "end": 4457 }
class ____(QueryExpectation): """Expect all values in a specific column to exist in another table's column. Args: template_dict: dict containing the following keys: \ first_table_column (name of the main table column), \ second_table_column (name of the column to compare to in the second table), \ second_table_full_name, \ condition (additional condition added in the where clause, provide "1=1" if not needed) """ library_metadata = { "tags": [ "query-based", ], "contributors": ["@itaise"], } metric_dependencies = ("query.template_values",) query = """ select count(1) from ( SELECT a.{first_table_column} FROM {batch} a LEFT JOIN {second_table_full_name} b ON a.{first_table_column}=b.{second_table_column} WHERE b.{second_table_column} IS NULL and {condition} GROUP BY 1 ) """ success_keys = ("template_dict", "query") domain_keys = ( "query", "template_dict", "batch_id", ) default_kwarg_values = { "result_format": "BASIC", "catch_exceptions": False, "meta": None, "query": query, } def _validate( self, metrics: dict, runtime_configuration: dict = None, execution_engine: ExecutionEngine = None, ) -> Union[ExpectationValidationResult, dict]: metrics = convert_to_json_serializable(data=metrics) num_of_missing_rows = list(metrics.get("query.template_values")[0].values())[0] return { "success": num_of_missing_rows == 0, "result": {"Rows with IDs in first table missing in second table": num_of_missing_rows}, } examples = [ { "data": [ { "data": { "msid": ["aaa", "bbb"], }, }, { "data": { "msid": ["aaa", "aaa"], }, }, { "data": { "msid": [ "aaa", "aaa", "aaa", "bbb", ], "date_created": [ "2022-02-02", "2022-02-02", "2022-02-02", "2022-02-02", ], }, }, ], "only_for": ["sqlite", "redshift"], "tests": [ { "title": "basic_negative_test", "exact_match_out": False, "include_in_gallery": True, "in": { "template_dict": { "second_table_full_name": "test_2", "first_table_column": "msid", "second_table_column": "msid", "condition": "1=1", }, }, "out": {"success": False}, }, { "title": "basic_positive_test", "exact_match_out": False, "include_in_gallery": True, "in": { "template_dict": { "second_table_full_name": "test_3", "first_table_column": "msid", "second_table_column": "msid", "condition": "date_created > date('2022-01-01')", } }, "out": {"success": True}, }, ], }, ] if __name__ == "__main__": ExpectQueriedColumnValuesToExistInSecondTableColumn().print_diagnostic_checklist()
ExpectQueriedColumnValuesToExistInSecondTableColumn
python
doocs__leetcode
solution/0600-0699/0677.Map Sum Pairs/Solution.py
{ "start": 629, "end": 1079 }
class ____: def __init__(self): self.d = defaultdict(int) self.tree = Trie() def insert(self, key: str, val: int) -> None: x = val - self.d[key] self.d[key] = val self.tree.insert(key, x) def sum(self, prefix: str) -> int: return self.tree.search(prefix) # Your MapSum object will be instantiated and called as such: # obj = MapSum() # obj.insert(key,val) # param_2 = obj.sum(prefix)
MapSum
python
dagster-io__dagster
python_modules/dagster/dagster_tests/execution_tests/misc_execution_tests/test_custom_reconstructable.py
{ "start": 162, "end": 2884 }
class ____: def __init__(self, prefix: str): self.prefix = prefix def make_job(self, has_nested_scope_solid: bool, name: str) -> dg.JobDefinition: @dg.op def nested_scope_op(_context): pass @dg.job(name=self.prefix + name) def _job(): if has_nested_scope_solid: nested_scope_op() top_scope_op() return _job def reconstruct_job(factory_prefix: str, has_nested_scope_op: bool, name: str) -> dg.JobDefinition: factory = JobFactory(factory_prefix) return factory.make_job(has_nested_scope_op, name=name) def test_build_reconstructable_job(): sys_path = sys.path try: factory = JobFactory("foo_") bar_job = factory.make_job(True, name="bar") with pytest.raises(dg.DagsterInvariantViolationError): dg.reconstructable(bar_job) reconstructable_bar_job = dg.build_reconstructable_job( "test_custom_reconstructable", "reconstruct_job", ("foo_",), {"has_nested_scope_op": True, "name": "bar"}, reconstructor_working_directory=os.path.dirname(os.path.realpath(__file__)), ) reconstructed_bar_job_def = reconstructable_bar_job.get_definition() assert reconstructed_bar_job_def.name == "foo_bar" assert len(reconstructed_bar_job_def.nodes) == 2 assert reconstructed_bar_job_def.get_node_named("top_scope_op") assert reconstructed_bar_job_def.get_node_named("nested_scope_op") finally: sys.path = sys_path def test_build_reconstructable_job_serdes(): sys_path = sys.path try: factory = JobFactory("foo_") bar_job = factory.make_job(True, name="bar") with pytest.raises(dg.DagsterInvariantViolationError): dg.reconstructable(bar_job) sys.path.insert(0, os.path.dirname(os.path.realpath(__file__))) reconstructable_bar_job = dg.build_reconstructable_job( "test_custom_reconstructable", "reconstruct_job", ("foo_",), {"has_nested_scope_op": True, "name": "bar"}, ) reconstructable_bar_job_dict = reconstructable_bar_job.to_dict() reconstructed_bar_job = ReconstructableJob.from_dict(reconstructable_bar_job_dict) reconstructed_bar_job_def = reconstructed_bar_job.get_definition() assert reconstructed_bar_job_def.name == "foo_bar" assert len(reconstructed_bar_job_def.nodes) == 2 assert reconstructed_bar_job_def.get_node_named("top_scope_op") assert reconstructed_bar_job_def.get_node_named("nested_scope_op") finally: sys.path = sys_path
JobFactory
python
getsentry__sentry
src/sentry/releases/migrations/0004_cleanup_failed_safe_deletes.py
{ "start": 207, "end": 1900 }
class ____(CheckedMigration): # This flag is used to mark that a migration shouldn't be automatically run in production. # This should only be used for operations where it's safe to run the migration after your # code has deployed. So this should not be used for most operations that alter the schema # of a table. # Here are some things that make sense to mark as post deployment: # - Large data migrations. Typically we want these to be run manually so that they can be # monitored and not block the deploy for a long period of time while they run. # - Adding indexes to large tables. Since this can take a long time, we'd generally prefer to # run this outside deployments so that we don't block them. Note that while adding an index # is a schema change, it's completely safe to run the operation after the code has deployed. # Once deployed, run these manually via: https://develop.sentry.dev/database-migrations/#migration-deployment is_post_deployment = False dependencies = [ ("releases", "0003_real_delete_dual_written_commit_tables"), ] operations = [ # Clean up tables that may not have been deleted due to missing # historical_silo_assignments entries before the fix SafeRunSQL( sql="DROP TABLE IF EXISTS releases_commit CASCADE;", reverse_sql=migrations.RunSQL.noop, hints={"tables": ["releases_commit"]}, ), SafeRunSQL( sql="DROP TABLE IF EXISTS releases_commitfilechange CASCADE;", reverse_sql=migrations.RunSQL.noop, hints={"tables": ["releases_commitfilechange"]}, ), ]
Migration
python
apache__avro
lang/py/avro/test/test_protocol.py
{ "start": 15919, "end": 17237 }
class ____(unittest.TestCase): """Enable generating round-trip parse test cases over all the valid test protocols.""" def __init__(self, test_proto): """Ignore the normal signature for unittest.TestCase because we are generating many test cases from this one class. This is safe as long as the autoloader ignores this class. The autoloader will ignore this class as long as it has no methods starting with `test_`. """ super().__init__("parse_round_trip") self.test_proto = test_proto def parse_round_trip(self): """The string of a Protocol should be parseable to the same Protocol.""" parsed = self.test_proto.parse() round_trip = avro.protocol.parse(str(parsed)) self.assertEqual(parsed, round_trip) def load_tests(loader, default_tests, pattern): """Generate test cases across many test protocol.""" suite = unittest.TestSuite() suite.addTests(loader.loadTestsFromTestCase(TestMisc)) suite.addTests(ProtocolParseTestCase(ex) for ex in EXAMPLES) suite.addTests(RoundTripParseTestCase(ex) for ex in VALID_EXAMPLES) suite.addTests(ErrorProtocolTestCase(ex) for ex in VALID_EXAMPLES) return suite if __name__ == "__main__": # pragma: no coverage unittest.main()
RoundTripParseTestCase
python
kamyu104__LeetCode-Solutions
Python/best-time-to-buy-and-sell-stock.py
{ "start": 29, "end": 360 }
class ____(object): # @param prices, a list of integer # @return an integer def maxProfit(self, prices): max_profit, min_price = 0, float("inf") for price in prices: min_price = min(min_price, price) max_profit = max(max_profit, price - min_price) return max_profit
Solution
python
kamyu104__LeetCode-Solutions
Python/maximum-sum-score-of-array.py
{ "start": 48, "end": 517 }
class ____(object): def maximumSumScore(self, nums): """ :type nums: List[int] :rtype: int """ prefix = suffix = 0 result = float("-inf") right = len(nums)-1 for left in xrange(len(nums)): prefix += nums[left] suffix += nums[right] right -= 1 result = max(result, prefix, suffix) return result # Time: O(n) # Space: O(1) # prefix sum
Solution
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/protocol3.py
{ "start": 4942, "end": 5014 }
class ____: prop1: Final[int] = 0 @dataclass(frozen=True)
Concrete15_4
python
spack__spack
lib/spack/spack/vendor/jinja2/compiler.py
{ "start": 4497, "end": 4729 }
class ____: def __init__(self, node: t.Union[nodes.Macro, nodes.CallBlock]) -> None: self.node = node self.accesses_caller = False self.accesses_kwargs = False self.accesses_varargs = False
MacroRef
python
pytorch__pytorch
test/test_varlen_attention.py
{ "start": 4836, "end": 19564 }
class ____(NNTestCase): @skipIfRocm(msg="ROCM does not support variable length attention") @unittest.skipIf( not PLATFORM_SUPPORTS_FLASH_ATTENTION, "Flash Attention not supported" ) @parametrize("dtype", [torch.bfloat16, torch.float16]) def test_basic_functionality(self, device, dtype): torch.manual_seed(42) shape = VarlenShape(batch_size=2, max_seq_len=512, embed_dim=1024, num_heads=16) attention_block = AttentionBlock( shape.embed_dim, shape.num_heads, device, dtype ) total_tokens = shape.batch_size * shape.max_seq_len x_packed = torch.randn( total_tokens, shape.embed_dim, device=device, dtype=dtype, requires_grad=True, ) cu_seq = torch.tensor( [0, shape.max_seq_len, total_tokens], device=device, dtype=torch.int32 ) output = attention_block.forward_varlen( x_packed, cu_seq, shape.max_seq_len, is_causal=False ) self.assertEqual(output.shape, (total_tokens, shape.embed_dim)) self.assertEqual(output.device, torch.device(device)) self.assertEqual(output.dtype, dtype) varlen_grad_out = torch.ones_like(output) varlen_grad = torch.autograd.grad( outputs=output, inputs=x_packed, grad_outputs=varlen_grad_out, retain_graph=True, create_graph=False, allow_unused=False, )[0] self.assertIsNotNone(varlen_grad) self.assertEqual(varlen_grad.shape, x_packed.shape) self.assertEqual(varlen_grad.dtype, x_packed.dtype) @skipIfRocm(msg="ROCM does not support variable length attention") @unittest.skipIf( not PLATFORM_SUPPORTS_FLASH_ATTENTION, "Flash Attention not supported" ) @parametrize("dtype", [torch.bfloat16, torch.float16]) def test_custom_op_compliance(self, device, dtype): torch.manual_seed(42) shape = VarlenShape(batch_size=2, max_seq_len=512, embed_dim=1024, num_heads=16) attention_block = AttentionBlock( shape.embed_dim, shape.num_heads, device, dtype ) total_tokens = shape.batch_size * shape.max_seq_len x_packed = torch.randn( total_tokens, shape.embed_dim, device=device, dtype=dtype, ) cu_seq = torch.tensor( [0, shape.max_seq_len, total_tokens], device=device, dtype=torch.int32 ) q, k, v = attention_block.get_varlen_qkv(x_packed) torch.library.opcheck( torch.ops.torch_attn._varlen_attn, (q, k, v, cu_seq, cu_seq, shape.max_seq_len, shape.max_seq_len, False), ) out, lse, rng_state = torch.ops.torch_attn._varlen_attn( q, k, v, cu_seq, cu_seq, shape.max_seq_len, shape.max_seq_len, False ) grad_out = torch.randn_like(out) # we don't support double backward # skipping test_autograd_registration, test_aot_dispatch_dynamic, test_aot_dispatch_static torch.library.opcheck( torch.ops.torch_attn._varlen_attn_backward, ( grad_out, q, k, v, out, lse, cu_seq, cu_seq, shape.max_seq_len, shape.max_seq_len, False, rng_state, ), test_utils=["test_schema", "test_faketensor"], ) @skipIfRocm(msg="ROCM does not support variable length attention") @unittest.skipIf( not PLATFORM_SUPPORTS_FLASH_ATTENTION, "Flash Attention not supported" ) @parametrize("dtype", [torch.bfloat16, torch.float16]) def test_custom_op_registration(self, device, dtype): torch.manual_seed(42) shape = VarlenShape(batch_size=2, max_seq_len=512, embed_dim=1024, num_heads=16) attention_block = AttentionBlock( shape.embed_dim, shape.num_heads, device, dtype ) total_tokens = shape.batch_size * shape.max_seq_len x_packed = torch.randn( total_tokens, shape.embed_dim, device=device, dtype=dtype, requires_grad=True, ) cu_seq = torch.tensor( [0, shape.max_seq_len, total_tokens], device=device, dtype=torch.int32 ) compiled_forward = torch.compile( attention_block.forward_varlen, backend="eager", fullgraph=True ) with OpLoggingMode() as mode: output = compiled_forward( x_packed, cu_seq, shape.max_seq_len, is_causal=False ) varlen_grad_out = torch.ones_like(output) _ = torch.autograd.grad( outputs=output, inputs=x_packed, grad_outputs=varlen_grad_out, retain_graph=True, create_graph=False, allow_unused=False, )[0] called_ops = mode.called_ops custom_ops_called = any( "torch_attn._varlen_attn" in op for op in called_ops ) and any("torch_attn._varlen_attn_backward" in op for op in called_ops) assert custom_ops_called @skipIfRocm(msg="ROCM does not support variable length attention") @unittest.skipIf( not PLATFORM_SUPPORTS_FLASH_ATTENTION, "Flash Attention not supported" ) @parametrize("dtype", [torch.bfloat16, torch.float16]) @parametrize("is_causal", [False, True]) def test_varlen_vs_sdpa(self, device, dtype, is_causal): torch.manual_seed(42) shape = VarlenShape( batch_size=8, max_seq_len=2048, embed_dim=1024, num_heads=16 ) attention_block = AttentionBlock( shape.embed_dim, shape.num_heads, device, dtype ) golden_attention_block = AttentionBlock( shape.embed_dim, shape.num_heads, device, torch.float32 ) variable_length_batch_data = create_variable_length_batch(shape, device, dtype) golden_variable_length_batch_data = create_variable_length_batch( shape, device, torch.float32 ) varlen_output = attention_block.forward_varlen( variable_length_batch_data["x_packed"], variable_length_batch_data["cu_seq"], variable_length_batch_data["max_len"], is_causal=is_causal, ) sdpa_output = attention_block.forward_sdpa( variable_length_batch_data["x_padded"], variable_length_batch_data["seq_lengths"], is_causal=is_causal, ) golden_sdpa_output = golden_attention_block.forward_sdpa( golden_variable_length_batch_data["x_padded"], golden_variable_length_batch_data["seq_lengths"], is_causal=is_causal, ) start_idx = 0 for i, seq_len in enumerate(variable_length_batch_data["seq_lengths"]): end_idx = start_idx + seq_len varlen_seq = varlen_output[start_idx:end_idx] sdpa_seq = sdpa_output[i, :seq_len] golden_sdpa_seq = golden_sdpa_output[i, :seq_len] fwd_atol = ( 2 * (golden_sdpa_seq + 0.3 - 0.3 - golden_sdpa_seq).abs().max().item() ) varlen_error = (varlen_seq - fwd_atol).abs().max().item() sdpa_error = (sdpa_seq - fwd_atol).abs().max().item() assert varlen_error <= 2 * sdpa_error + fwd_atol start_idx = end_idx varlen_grad_out = torch.ones_like(varlen_output) sdpa_grad_out = torch.ones_like(sdpa_output) golden_sdpa_grad_out = torch.ones_like(golden_sdpa_output) start_idx = 0 for i, seq_len in enumerate(variable_length_batch_data["seq_lengths"]): end_idx = start_idx + seq_len sdpa_grad_out[i, :seq_len] = varlen_grad_out[start_idx:end_idx] start_idx = end_idx varlen_grad = torch.autograd.grad( outputs=varlen_output, inputs=variable_length_batch_data["x_packed"], grad_outputs=varlen_grad_out, retain_graph=True, create_graph=False, allow_unused=False, )[0] sdpa_grad = torch.autograd.grad( outputs=sdpa_output, inputs=variable_length_batch_data["x_padded"], grad_outputs=sdpa_grad_out, retain_graph=True, create_graph=False, allow_unused=False, )[0] golden_sdpa_grad = torch.autograd.grad( outputs=golden_sdpa_output, inputs=golden_variable_length_batch_data["x_padded"], grad_outputs=golden_sdpa_grad_out, retain_graph=True, create_graph=False, allow_unused=False, )[0] start_idx = 0 for i, seq_len in enumerate(variable_length_batch_data["seq_lengths"]): end_idx = start_idx + seq_len varlen_grad_seq = varlen_grad[start_idx:end_idx] sdpa_grad_seq = sdpa_grad[i, :seq_len] golden_sdpa_seq = golden_sdpa_grad[i, :seq_len] fwd_atol = ( 2 * (golden_sdpa_seq + 0.3 - 0.3 - golden_sdpa_seq).abs().max().item() ) varlen_error = (varlen_grad_seq - fwd_atol).abs().max().item() sdpa_error = (sdpa_grad_seq - fwd_atol).abs().max().item() assert varlen_error <= sdpa_error + fwd_atol start_idx = end_idx @skipIfRocm(msg="ROCM does not support variable length attention") @unittest.skipIf( not PLATFORM_SUPPORTS_FLASH_ATTENTION, "Flash Attention not supported" ) @parametrize("dtype", [torch.bfloat16, torch.float16]) @parametrize("is_causal", [False, True]) @parametrize("num_perms", [1, 3, 5]) def test_batch_invariance(self, device, dtype, is_causal, num_perms): torch.manual_seed(42) batch_size, max_seq_len = 4, 128 seq_lengths = [] for _ in range(batch_size): length = torch.randint(1, max_seq_len // 64 + 1, (1,)).item() * 64 seq_lengths.append(min(length, max_seq_len)) sequences_qkv = [ [ torch.testing.make_tensor( (seq_len, 2, 128), device=device, dtype=dtype, requires_grad=True ) for _ in range(3) ] for seq_len in seq_lengths ] sequences_q, sequences_k, sequences_v = map(list, zip(*sequences_qkv)) q_packed_orig = torch.cat(sequences_q, dim=0) k_packed_orig = torch.cat(sequences_k, dim=0) v_packed_orig = torch.cat(sequences_v, dim=0) seq_lens = torch.tensor(seq_lengths, device=device) cu_seq_orig = torch.zeros(batch_size + 1, device=device, dtype=torch.int32) cu_seq_orig[1:] = seq_lens.cumsum(0) original_output = varlen_attn( q_packed_orig, k_packed_orig, v_packed_orig, cu_seq_orig, cu_seq_orig, max_seq_len, max_seq_len, is_causal, ) original_grad_out = torch.randn_like(original_output) original_grads = torch.autograd.grad( outputs=original_output, inputs=[q_packed_orig, k_packed_orig, v_packed_orig], grad_outputs=original_grad_out, ) for _ in range(num_perms): perm = torch.randperm(batch_size) permuted_sequences_q = [sequences_q[perm[i]] for i in range(batch_size)] permuted_sequences_k = [sequences_k[perm[i]] for i in range(batch_size)] permuted_sequences_v = [sequences_v[perm[i]] for i in range(batch_size)] q_packed_perm = torch.cat(permuted_sequences_q, dim=0) k_packed_perm = torch.cat(permuted_sequences_k, dim=0) v_packed_perm = torch.cat(permuted_sequences_v, dim=0) permuted_seq_lens = torch.tensor( [seq_lengths[perm[i]] for i in range(batch_size)], device=device ) cu_seq_perm = torch.zeros(batch_size + 1, device=device, dtype=torch.int32) cu_seq_perm[1:] = permuted_seq_lens.cumsum(0) permuted_output = varlen_attn( q_packed_perm, k_packed_perm, v_packed_perm, cu_seq_perm, cu_seq_perm, max_seq_len, max_seq_len, is_causal, ) for i in range(batch_size): orig_idx = perm[i].item() orig_start = cu_seq_orig[orig_idx].item() orig_end = cu_seq_orig[orig_idx + 1].item() orig_seq_output = original_output[orig_start:orig_end] perm_start = cu_seq_perm[i].item() perm_end = cu_seq_perm[i + 1].item() perm_seq_output = permuted_output[perm_start:perm_end] self.assertEqual(orig_seq_output, perm_seq_output) permuted_grad_out = torch.zeros_like(permuted_output) for i in range(batch_size): orig_idx = perm[i].item() orig_start = cu_seq_orig[orig_idx].item() orig_end = cu_seq_orig[orig_idx + 1].item() perm_start = cu_seq_perm[i].item() perm_end = cu_seq_perm[i + 1].item() permuted_grad_out[perm_start:perm_end] = original_grad_out[ orig_start:orig_end ] permuted_grads = torch.autograd.grad( outputs=permuted_output, inputs=[q_packed_perm, k_packed_perm, v_packed_perm], grad_outputs=permuted_grad_out, ) for original_grad, permuted_grad in zip(original_grads, permuted_grads): for i in range(batch_size): orig_idx = perm[i].item() orig_start = cu_seq_orig[orig_idx].item() orig_end = cu_seq_orig[orig_idx + 1].item() orig_seq_grad = original_grad[orig_start:orig_end] perm_start = cu_seq_perm[i].item() perm_end = cu_seq_perm[i + 1].item() perm_seq_grad = permuted_grad[perm_start:perm_end] self.assertEqual(orig_seq_grad, perm_seq_grad) device_types = ("cuda",) instantiate_device_type_tests(TestVarlenAttention, globals(), only_for=device_types) if __name__ == "__main__": run_tests()
TestVarlenAttention
python
Textualize__textual
tests/option_list/test_option_list_create.py
{ "start": 289, "end": 6381 }
class ____(App[None]): """Test option list application.""" def compose(self) -> ComposeResult: yield OptionList( "0", Option("1"), None, Option("2", disabled=True), None, Option("3", id="3"), Option("4", id="4", disabled=True), ) async def test_all_parameters_become_options() -> None: """All input parameters to a list should become options.""" async with OptionListApp().run_test() as pilot: option_list = pilot.app.query_one(OptionList) assert option_list.option_count == 5 for n in range(5): assert isinstance(option_list.get_option_at_index(n), Option) async def test_id_capture() -> None: """All options given an ID should retain the ID.""" async with OptionListApp().run_test() as pilot: option_list = pilot.app.query_one(OptionList) with_id = 0 without_id = 0 for n in range(5): if option_list.get_option_at_index(n).id is None: without_id += 1 else: with_id += 1 assert with_id == 2 assert without_id == 3 async def test_get_option_by_id() -> None: """It should be possible to get an option by ID.""" async with OptionListApp().run_test() as pilot: option_list = pilot.app.query_one(OptionList) assert option_list.get_option("3").prompt == "3" assert option_list.get_option("4").prompt == "4" async def test_get_option_with_bad_id() -> None: """Asking for an option with a bad ID should give an error.""" async with OptionListApp().run_test() as pilot: with pytest.raises(OptionDoesNotExist): _ = pilot.app.query_one(OptionList).get_option("this does not exist") async def test_get_option_by_index() -> None: """It should be possible to get an option by index.""" async with OptionListApp().run_test() as pilot: option_list = pilot.app.query_one(OptionList) for n in range(5): assert option_list.get_option_at_index(n).prompt == str(n) assert option_list.get_option_at_index(-1).prompt == "4" async def test_get_option_at_bad_index() -> None: """Asking for an option at a bad index should give an error.""" async with OptionListApp().run_test() as pilot: with pytest.raises(OptionDoesNotExist): _ = pilot.app.query_one(OptionList).get_option_at_index(42) with pytest.raises(OptionDoesNotExist): _ = pilot.app.query_one(OptionList).get_option_at_index(-42) async def test_clear_option_list() -> None: """It should be possible to clear the option list of all content.""" async with OptionListApp().run_test() as pilot: option_list = pilot.app.query_one(OptionList) assert option_list.option_count == 5 option_list.clear_options() assert option_list.option_count == 0 async def test_add_later() -> None: """It should be possible to add more items to a list.""" async with OptionListApp().run_test() as pilot: option_list = pilot.app.query_one(OptionList) assert option_list.option_count == 5 option_list.add_option("more") assert option_list.option_count == 6 option_list.add_option() assert option_list.option_count == 6 option_list.add_option(Option("even more")) assert option_list.option_count == 7 option_list.add_options( [Option("more still"), "Yet more options", "so many options!"] ) assert option_list.option_count == 10 option_list.add_option(None) assert option_list.option_count == 10 option_list.add_options([]) assert option_list.option_count == 10 async def test_create_with_duplicate_id() -> None: """Adding an option with a duplicate ID should be an error.""" async with OptionListApp().run_test() as pilot: option_list = pilot.app.query_one(OptionList) assert option_list.option_count == 5 with pytest.raises(DuplicateID): option_list.add_option(Option("dupe", id="3")) assert option_list.option_count == 5 async def test_create_with_duplicate_id_and_subsequent_non_dupes() -> None: """Adding an option with a duplicate ID should be an error.""" async with OptionListApp().run_test() as pilot: option_list = pilot.app.query_one(OptionList) assert option_list.option_count == 5 with pytest.raises(DuplicateID): option_list.add_option(Option("dupe", id="3")) assert option_list.option_count == 5 option_list.add_option(Option("Not a dupe", id="6")) assert option_list.option_count == 6 option_list.add_option(Option("Not a dupe", id="7")) assert option_list.option_count == 7 async def test_adding_multiple_duplicates_at_once() -> None: """Adding duplicates together than aren't existing duplicates should be an error.""" async with OptionListApp().run_test() as pilot: option_list = pilot.app.query_one(OptionList) assert option_list.option_count == 5 with pytest.raises(DuplicateID): option_list.add_options( [ Option("dupe", id="42"), Option("dupe", id="42"), ] ) assert option_list.option_count == 5 async def test_options_are_available_soon() -> None: """Regression test for https://github.com/Textualize/textual/issues/3903.""" option = Option("", id="some_id") option_list = OptionList(option) assert option_list.get_option("some_id") is option async def test_set_options(): """Test set_options method.""" async with OptionListApp().run_test() as pilot: option_list = pilot.app.query_one(OptionList) option_list.set_options(["foo", "bar"]) assert option_list.option_count == 2 assert option_list.get_option_at_index(0).prompt == "foo" assert option_list.get_option_at_index(1).prompt == "bar"
OptionListApp
python
sympy__sympy
sympy/holonomic/recurrence.py
{ "start": 2884, "end": 9036 }
class ____: """ The Recurrence Operators are defined by a list of polynomials in the base ring and the parent ring of the Operator. Explanation =========== Takes a list of polynomials for each power of Sn and the parent ring which must be an instance of RecurrenceOperatorAlgebra. A Recurrence Operator can be created easily using the operator `Sn`. See examples below. Examples ======== >>> from sympy.holonomic.recurrence import RecurrenceOperator, RecurrenceOperators >>> from sympy import ZZ >>> from sympy import symbols >>> n = symbols('n', integer=True) >>> R, Sn = RecurrenceOperators(ZZ.old_poly_ring(n),'Sn') >>> RecurrenceOperator([0, 1, n**2], R) (1)Sn + (n**2)Sn**2 >>> Sn*n (n + 1)Sn >>> n*Sn*n + 1 - Sn**2*n (1) + (n**2 + n)Sn + (-n - 2)Sn**2 See Also ======== DifferentialOperatorAlgebra """ _op_priority = 20 def __init__(self, list_of_poly, parent): # the parent ring for this operator # must be an RecurrenceOperatorAlgebra object self.parent = parent # sequence of polynomials in n for each power of Sn # represents the operator # convert the expressions into ring elements using from_sympy if isinstance(list_of_poly, list): for i, j in enumerate(list_of_poly): if isinstance(j, int): list_of_poly[i] = self.parent.base.from_sympy(S(j)) elif not isinstance(j, self.parent.base.dtype): list_of_poly[i] = self.parent.base.from_sympy(j) self.listofpoly = list_of_poly self.order = len(self.listofpoly) - 1 def __mul__(self, other): """ Multiplies two Operators and returns another RecurrenceOperator instance using the commutation rule Sn * a(n) = a(n + 1) * Sn """ listofself = self.listofpoly base = self.parent.base if not isinstance(other, RecurrenceOperator): if not isinstance(other, self.parent.base.dtype): listofother = [self.parent.base.from_sympy(sympify(other))] else: listofother = [other] else: listofother = other.listofpoly # multiply a polynomial `b` with a list of polynomials def _mul_dmp_diffop(b, listofother): if isinstance(listofother, list): return [i * b for i in listofother] return [b * listofother] sol = _mul_dmp_diffop(listofself[0], listofother) # compute Sn^i * b def _mul_Sni_b(b): sol = [base.zero] if isinstance(b, list): for i in b: j = base.to_sympy(i).subs(base.gens[0], base.gens[0] + S.One) sol.append(base.from_sympy(j)) else: j = b.subs(base.gens[0], base.gens[0] + S.One) sol.append(base.from_sympy(j)) return sol for i in range(1, len(listofself)): # find Sn^i * b in ith iteration listofother = _mul_Sni_b(listofother) # solution = solution + listofself[i] * (Sn^i * b) sol = _add_lists(sol, _mul_dmp_diffop(listofself[i], listofother)) return RecurrenceOperator(sol, self.parent) def __rmul__(self, other): if not isinstance(other, RecurrenceOperator): if isinstance(other, int): other = S(other) if not isinstance(other, self.parent.base.dtype): other = (self.parent.base).from_sympy(other) sol = [other * j for j in self.listofpoly] return RecurrenceOperator(sol, self.parent) def __add__(self, other): if isinstance(other, RecurrenceOperator): sol = _add_lists(self.listofpoly, other.listofpoly) return RecurrenceOperator(sol, self.parent) else: if isinstance(other, int): other = S(other) list_self = self.listofpoly if not isinstance(other, self.parent.base.dtype): list_other = [((self.parent).base).from_sympy(other)] else: list_other = [other] sol = [list_self[0] + list_other[0]] + list_self[1:] return RecurrenceOperator(sol, self.parent) __radd__ = __add__ def __sub__(self, other): return self + (-1) * other def __rsub__(self, other): return (-1) * self + other def __pow__(self, n): if n == 1: return self result = RecurrenceOperator([self.parent.base.one], self.parent) if n == 0: return result # if self is `Sn` if self.listofpoly == self.parent.shift_operator.listofpoly: sol = [self.parent.base.zero] * n + [self.parent.base.one] return RecurrenceOperator(sol, self.parent) x = self while True: if n % 2: result *= x n >>= 1 if not n: break x *= x return result def __str__(self): listofpoly = self.listofpoly print_str = '' for i, j in enumerate(listofpoly): if j == self.parent.base.zero: continue j = self.parent.base.to_sympy(j) if i == 0: print_str += '(' + sstr(j) + ')' continue if print_str: print_str += ' + ' if i == 1: print_str += '(' + sstr(j) + ')Sn' continue print_str += '(' + sstr(j) + ')' + 'Sn**' + sstr(i) return print_str __repr__ = __str__ def __eq__(self, other): if isinstance(other, RecurrenceOperator): if self.listofpoly == other.listofpoly and self.parent == other.parent: return True else: return False return self.listofpoly[0] == other and \ all(i is self.parent.base.zero for i in self.listofpoly[1:])
RecurrenceOperator
python
vyperlang__vyper
vyper/venom/basicblock.py
{ "start": 5447, "end": 5902 }
class ____(IROperand): """ IRVariable represents a variable in IR. A variable is a string that starts with a %. """ _name: str def __init__(self, name: str) -> None: assert isinstance(name, str) # name = name.removeprefix("%") if not name.startswith("%"): name = f"%{name}" super().__init__(name) @property def plain_name(self) -> str: return self.name.strip("%")
IRVariable
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/metadata.py
{ "start": 1924, "end": 2123 }
class ____(graphene.ObjectType): text = graphene.NonNull(graphene.String) class Meta: interfaces = (GrapheneMetadataEntry,) name = "TextMetadataEntry"
GrapheneTextMetadataEntry
python
kamyu104__LeetCode-Solutions
Python/construct-binary-tree-from-inorder-and-postorder-traversal.py
{ "start": 153, "end": 982 }
class ____(object): # @param inorder, a list of integers # @param postorder, a list of integers # @return a tree node def buildTree(self, inorder, postorder): lookup = {} for i, num in enumerate(inorder): lookup[num] = i return self.buildTreeRecu(lookup, postorder, inorder, len(postorder), 0, len(inorder)) def buildTreeRecu(self, lookup, postorder, inorder, post_end, in_start, in_end): if in_start == in_end: return None node = TreeNode(postorder[post_end - 1]) i = lookup[postorder[post_end - 1]] node.left = self.buildTreeRecu(lookup, postorder, inorder, post_end - 1 - (in_end - i - 1), in_start, i) node.right = self.buildTreeRecu(lookup, postorder, inorder, post_end - 1, i + 1, in_end) return node
Solution
python
great-expectations__great_expectations
great_expectations/checkpoint/checkpoint.py
{ "start": 20640, "end": 20814 }
class ____(TypedDict): evaluated_validations: int success_percent: float successful_validations: int unsuccessful_validations: int
CheckpointDescriptionStatistics
python
getsentry__sentry
src/sentry/integrations/pagerduty/handlers/pagerduty_handler.py
{ "start": 812, "end": 1808 }
class ____(IntegrationActionHandler): group = ActionHandler.Group.NOTIFICATION provider_slug = IntegrationProviderSlug.PAGERDUTY config_schema = ONCALL_ACTION_CONFIG_SCHEMA data_schema = { "$schema": "https://json-schema.org/draft/2020-12/schema", "type": "object", "properties": { "priority": { "type": "string", "description": "The priority of the pagerduty action", "enum": [severity for severity in PagerdutySeverity], }, "additionalProperties": False, }, } @staticmethod def get_config_transformer() -> ConfigTransformer | None: return TargetTypeConfigTransformer.from_config_schema(PagerdutyActionHandler.config_schema) @staticmethod def execute( job: WorkflowEventData, action: Action, detector: Detector, ) -> None: execute_via_group_type_registry(job, action, detector)
PagerdutyActionHandler
python
ray-project__ray
python/ray/util/collective/tests/cpu_util.py
{ "start": 214, "end": 4477 }
class ____: def __init__(self): self.buffer = None self.list_buffer = None def init_tensors(self): self.buffer = np.ones((10,), dtype=np.float32) self.list_buffer = [np.ones((10,), dtype=np.float32) for _ in range(2)] return True def init_group(self, world_size, rank, backend=Backend.NCCL, group_name="default"): col.init_collective_group(world_size, rank, backend, group_name) return True def set_buffer(self, data): self.buffer = data return self.buffer def get_buffer(self): return self.buffer def set_list_buffer(self, list_of_arrays, copy=False): if copy: copy_list = [] for tensor in list_of_arrays: if isinstance(tensor, np.ndarray): copy_list.append(tensor.copy()) elif isinstance(tensor, torch.Tensor): copy_list.append(tensor.clone().detach()) self.list_buffer = copy_list else: self.list_buffer = list_of_arrays return self.list_buffer def do_allreduce(self, group_name="default", op=ReduceOp.SUM): col.allreduce(self.buffer, group_name, op) return self.buffer def do_reduce(self, group_name="default", dst_rank=0, op=ReduceOp.SUM): col.reduce(self.buffer, dst_rank, group_name, op) return self.buffer def do_broadcast(self, group_name="default", src_rank=0): col.broadcast(self.buffer, src_rank, group_name) return self.buffer def do_allgather(self, group_name="default"): col.allgather(self.list_buffer, self.buffer, group_name) return self.list_buffer def do_reducescatter(self, group_name="default", op=ReduceOp.SUM): col.reducescatter(self.buffer, self.list_buffer, group_name, op) return self.buffer def do_send(self, group_name="default", dst_rank=0): col.send(self.buffer, dst_rank, group_name) return self.buffer def do_recv(self, group_name="default", src_rank=0): col.recv(self.buffer, src_rank, group_name) return self.buffer def destroy_group(self, group_name="default"): col.destroy_collective_group(group_name) return True def report_rank(self, group_name="default"): rank = col.get_rank(group_name) return rank def report_world_size(self, group_name="default"): ws = col.get_collective_group_size(group_name) return ws def report_nccl_availability(self): avail = col.nccl_available() return avail def report_gloo_availability(self): avail = col.gloo_available() return avail def report_is_group_initialized(self, group_name="default"): is_init = col.is_group_initialized(group_name) return is_init def create_collective_workers(num_workers=2, group_name="default", backend="nccl"): actors = [None] * num_workers for i in range(num_workers): actor = Worker.remote() ray.get([actor.init_tensors.remote()]) actors[i] = actor world_size = num_workers init_results = ray.get( [ actor.init_group.remote(world_size, i, backend, group_name) for i, actor in enumerate(actors) ] ) return actors, init_results def init_tensors_for_gather_scatter( actors, array_size=10, dtype=np.float32, tensor_backend="numpy" ): world_size = len(actors) for i, a in enumerate(actors): if tensor_backend == "numpy": t = np.ones(array_size, dtype=dtype) * (i + 1) elif tensor_backend == "torch": t = torch.ones(array_size, dtype=torch.float32) * (i + 1) else: raise RuntimeError("Unsupported tensor backend.") ray.get([a.set_buffer.remote(t)]) if tensor_backend == "numpy": list_buffer = [np.ones(array_size, dtype=dtype) for _ in range(world_size)] elif tensor_backend == "torch": list_buffer = [ torch.ones(array_size, dtype=torch.float32) for _ in range(world_size) ] else: raise RuntimeError("Unsupported tensor backend.") ray.get([a.set_list_buffer.remote(list_buffer, copy=True) for a in actors])
Worker
python
pydantic__pydantic
tests/mypy/outputs/mypy-plugin-strict_ini/plugin_fail.py
{ "start": 2599, "end": 2744 }
class ____(BaseModel, from_attributes=list): # MYPY: error: Invalid value for "Config.from_attributes" [pydantic-config] pass
KwargsBadConfig2
python
sympy__sympy
sympy/physics/quantum/hilbert.py
{ "start": 5337, "end": 6725 }
class ____(HilbertSpace): """The Hilbert space of square integrable functions on an interval. An L2 object takes in a single SymPy Interval argument which represents the interval its functions (vectors) are defined on. Examples ======== >>> from sympy import Interval, oo >>> from sympy.physics.quantum.hilbert import L2 >>> hs = L2(Interval(0,oo)) >>> hs L2(Interval(0, oo)) >>> hs.dimension oo >>> hs.interval Interval(0, oo) """ def __new__(cls, interval): if not isinstance(interval, Interval): raise TypeError('L2 interval must be an Interval instance: %r' % interval) obj = Basic.__new__(cls, interval) return obj @property def dimension(self): return S.Infinity @property def interval(self): return self.args[0] def _sympyrepr(self, printer, *args): return "L2(%s)" % printer._print(self.interval, *args) def _sympystr(self, printer, *args): return "L2(%s)" % printer._print(self.interval, *args) def _pretty(self, printer, *args): pform_exp = prettyForm('2') pform_base = prettyForm('L') return pform_base**pform_exp def _latex(self, printer, *args): interval = printer._print(self.interval, *args) return r'{\mathcal{L}^2}\left( %s \right)' % interval
L2
python
google__jax
jax/_src/state/types.py
{ "start": 2048, "end": 2099 }
class ____(RefEffect): name: str = "Read"
ReadEffect
python
apache__airflow
providers/google/tests/unit/google/cloud/triggers/test_vertex_ai.py
{ "start": 9017, "end": 11624 }
class ____: def setup_method(self): self.trigger = CreateHyperparameterTuningJobTrigger( conn_id=TEST_CONN_ID, project_id=TEST_PROJECT_ID, location=TEST_LOCATION, job_id=TEST_HPT_JOB_ID, poll_interval=TEST_POLL_INTERVAL, impersonation_chain=TEST_IMPERSONATION_CHAIN, ) def test_class_attributes(self): assert self.trigger.trigger_class_path == ( "airflow.providers.google.cloud.triggers.vertex_ai.CreateHyperparameterTuningJobTrigger" ) assert self.trigger.job_type_verbose_name == "Hyperparameter Tuning Job" assert self.trigger.job_serializer_class == HyperparameterTuningJob @mock.patch(VERTEX_AI_TRIGGER_PATH.format("HyperparameterTuningJobAsyncHook")) def test_async_hook(self, mock_async_hook): async_hook_actual = self.trigger.async_hook mock_async_hook.assert_called_once_with( gcp_conn_id=self.trigger.conn_id, impersonation_chain=self.trigger.impersonation_chain, ) assert async_hook_actual == mock_async_hook.return_value @pytest.mark.asyncio @mock.patch( VERTEX_AI_TRIGGER_PATH.format("HyperparameterTuningJobAsyncHook.wait_hyperparameter_tuning_job") ) async def test_wait_job(self, mock_wait_hyperparameter_tuning_job): job_expected = mock.MagicMock() async_mock = mock.AsyncMock(return_value=job_expected) mock_wait_hyperparameter_tuning_job.side_effect = async_mock with mock.patch( BASE_STRING.format("GoogleBaseHook.__init__"), new=mock_base_gcp_hook_default_project_id ): job_actual = await self.trigger._wait_job() mock_wait_hyperparameter_tuning_job.assert_awaited_once_with( project_id=self.trigger.project_id, location=self.trigger.location, job_id=self.trigger.job_id, poll_interval=self.trigger.poll_interval, ) assert job_actual == job_expected def test_serialize(self): classpath, kwargs = self.trigger.serialize() assert ( classpath == "airflow.providers.google.cloud.triggers.vertex_ai.CreateHyperparameterTuningJobTrigger" ) assert kwargs == dict( conn_id=TEST_CONN_ID, project_id=TEST_PROJECT_ID, location=TEST_LOCATION, job_id=TEST_HPT_JOB_ID, poll_interval=TEST_POLL_INTERVAL, impersonation_chain=TEST_IMPERSONATION_CHAIN, )
TestCreateHyperparameterTuningJobTrigger
python
apache__airflow
airflow-ctl/src/airflowctl/api/datamodels/generated.py
{ "start": 32714, "end": 33703 }
class ____(BaseModel): """ Asset event serializer for responses. """ id: Annotated[int, Field(title="Id")] asset_id: Annotated[int, Field(title="Asset Id")] uri: Annotated[str | None, Field(title="Uri")] = None name: Annotated[str | None, Field(title="Name")] = None group: Annotated[str | None, Field(title="Group")] = None extra: Annotated[dict[str, JsonValue] | None, Field(title="Extra")] = None source_task_id: Annotated[str | None, Field(title="Source Task Id")] = None source_dag_id: Annotated[str | None, Field(title="Source Dag Id")] = None source_run_id: Annotated[str | None, Field(title="Source Run Id")] = None source_map_index: Annotated[int, Field(title="Source Map Index")] created_dagruns: Annotated[list[DagRunAssetReference], Field(title="Created Dagruns")] timestamp: Annotated[datetime, Field(title="Timestamp")] partition_key: Annotated[str | None, Field(title="Partition Key")] = None
AssetEventResponse
python
sphinx-doc__sphinx
tests/roots/test-inheritance/dummy/test.py
{ "start": 205, "end": 231 }
class ____(B, C): pass
D
python
ray-project__ray
python/ray/autoscaler/v2/instance_manager/subscribers/threaded_ray_installer.py
{ "start": 708, "end": 3307 }
class ____(InstanceUpdatedSubscriber): """ThreadedRayInstaller is responsible for install ray on new nodes.""" def __init__( self, head_node_ip: str, instance_storage: InstanceStorage, ray_installer: RayInstaller, error_queue: Queue, max_install_attempts: int = 3, install_retry_interval: int = 10, max_concurrent_installs: int = 50, ) -> None: self._head_node_ip = head_node_ip self._instance_storage = instance_storage self._ray_installer = ray_installer self._max_concurrent_installs = max_concurrent_installs self._max_install_attempts = max_install_attempts self._install_retry_interval = install_retry_interval self._error_queue = error_queue self._ray_installation_executor = ThreadPoolExecutor( max_workers=self._max_concurrent_installs ) def notify(self, events: List[InstanceUpdateEvent]) -> None: for event in events: if event.new_instance_status == Instance.RAY_INSTALLING: self._install_ray_on_new_nodes(event.instance_id) def _install_ray_on_new_nodes(self, instance_id: str) -> None: allocated_instance, _ = self._instance_storage.get_instances( instance_ids={instance_id}, status_filter={Instance.RAY_INSTALLING}, ) for instance in allocated_instance.values(): assert instance.node_kind == NodeKind.WORKER self._ray_installation_executor.submit( self._install_ray_on_single_node, instance ) def _install_ray_on_single_node(self, instance: Instance) -> None: assert instance.status == Instance.RAY_INSTALLING # install with exponential backoff backoff_factor = 1 last_exception = None for _ in range(self._max_install_attempts): try: self._ray_installer.install_ray(instance, self._head_node_ip) return except Exception as e: logger.info( f"Ray installation failed on instance {instance.cloud_instance_id}: {e}" ) last_exception = e logger.warning("Failed to install ray, retrying...") time.sleep(self._install_retry_interval * backoff_factor) backoff_factor *= 2 self._error_queue.put_nowait( RayInstallError( im_instance_id=instance.instance_id, details=str(last_exception), ) )
ThreadedRayInstaller
python
great-expectations__great_expectations
great_expectations/expectations/core/expect_column_values_to_be_in_type_list.py
{ "start": 2926, "end": 27743 }
class ____(ColumnMapExpectation): __doc__ = f"""{EXPECTATION_SHORT_DESCRIPTION} ExpectColumnValuesToBeInTypeList is a \ Column Map Expectation \ for typed-column backends, and also for Pandas Datasources where the column dtype provides an \ unambiguous constraints (any dtype except 'object'). For Pandas columns with dtype of 'object' ExpectColumnValuesToBeInTypeList will \ independently check each row's type. Column Map Expectations are one of the most common types of Expectation. They are evaluated for a single column and ask a yes/no question for every row in that column. Based on the result, they then calculate the percentage of rows that gave a positive answer. If the percentage is high enough, the Expectation considers that data valid. Args: column (str): \ {COLUMN_DESCRIPTION} type_list (list[str] or None): \ {TYPE_LIST_DESCRIPTION} For example, valid types for Pandas Datasources include any numpy dtype values \ (such as 'int64') or native python types (such as 'int'), whereas valid types for a \ SqlAlchemy Datasource include types named by the current driver such as 'INTEGER' \ in most SQL dialects and 'TEXT' in dialects such as postgresql. Valid types for \ Spark Datasources include 'StringType', 'BooleanType' and other pyspark-defined type names. Other Parameters: mostly (None or a float between 0 and 1): \ Successful if at least mostly fraction of values match the expectation. \ For more detail, see [mostly](https://docs.greatexpectations.io/docs/reference/expectations/standard_arguments/#mostly). Default 1. result_format (str or None): \ Which output mode to use: BOOLEAN_ONLY, BASIC, COMPLETE, or SUMMARY. \ For more detail, see [result_format](https://docs.greatexpectations.io/docs/reference/expectations/result_format). catch_exceptions (boolean or None): \ If True, then catch exceptions and include them as part of the result object. \ For more detail, see [catch_exceptions](https://docs.greatexpectations.io/docs/reference/expectations/standard_arguments/#catch_exceptions). meta (dict or None): \ A JSON-serializable dictionary (nesting allowed) that will be included in the output without \ modification. For more detail, see [meta](https://docs.greatexpectations.io/docs/reference/expectations/standard_arguments/#meta). severity (str or None): \ {FAILURE_SEVERITY_DESCRIPTION} \ For more detail, see [failure severity](https://docs.greatexpectations.io/docs/cloud/expectations/expectations_overview/#failure-severity). Returns: An [ExpectationSuiteValidationResult](https://docs.greatexpectations.io/docs/terms/validation_result) Exact fields vary depending on the values passed to result_format, catch_exceptions, and meta. See also: [ExpectColumnValuesToBeOfType](https://greatexpectations.io/expectations/expect_column_values_to_be_of_type) Supported Data Sources: [{SUPPORTED_DATA_SOURCES[0]}](https://docs.greatexpectations.io/docs/application_integration_support/) [{SUPPORTED_DATA_SOURCES[1]}](https://docs.greatexpectations.io/docs/application_integration_support/) [{SUPPORTED_DATA_SOURCES[2]}](https://docs.greatexpectations.io/docs/application_integration_support/) [{SUPPORTED_DATA_SOURCES[3]}](https://docs.greatexpectations.io/docs/application_integration_support/) [{SUPPORTED_DATA_SOURCES[4]}](https://docs.greatexpectations.io/docs/application_integration_support/) [{SUPPORTED_DATA_SOURCES[5]}](https://docs.greatexpectations.io/docs/application_integration_support/) [{SUPPORTED_DATA_SOURCES[6]}](https://docs.greatexpectations.io/docs/application_integration_support/) [{SUPPORTED_DATA_SOURCES[7]}](https://docs.greatexpectations.io/docs/application_integration_support/) [{SUPPORTED_DATA_SOURCES[8]}](https://docs.greatexpectations.io/docs/application_integration_support/) Data Quality Issues: {DATA_QUALITY_ISSUES[0]} Example Data: test test2 0 "12345" 1 1 "abcde" 2 2 "1b3d5" 3 Code Examples: Passing Case: Input: ExpectColumnValuesToBeInTypeList( column="test2", type_list=["NUMBER", "STRING"] ) Output: {{ "exception_info": {{ "raised_exception": false, "exception_traceback": null, "exception_message": null }}, "result": {{ "element_count": 3, "unexpected_count": 0, "unexpected_percent": 0.0, "partial_unexpected_list": [], "missing_count": 0, "missing_percent": 0.0, "unexpected_percent_total": 0.0, "unexpected_percent_nonmissing": 0.0 }}, "meta": {{}}, "success": true }} Failing Case: Input: ExpectColumnValuesToBeInTypeList( column="test", type_list=["NUMBER", "DOUBLE"] ) Output: {{ "exception_info": {{ "raised_exception": false, "exception_traceback": null, "exception_message": null }}, "result": {{ "element_count": 3, "unexpected_count": 3, "unexpected_percent": 100.0, "partial_unexpected_list": [ "12345", "abcde", "1b3d5" ], "missing_count": 0, "missing_percent": 0.0, "unexpected_percent_total": 100.0, "unexpected_percent_nonmissing": 100.0 }}, "meta": {{}}, "success": false }} """ # noqa: E501 # FIXME CoP type_list: Union[List[str], SuiteParameterDict, None] = pydantic.Field( description=TYPE_LIST_DESCRIPTION ) library_metadata: ClassVar[Dict[str, Union[str, list, bool]]] = { "maturity": "production", "tags": ["core expectation", "column map expectation"], "contributors": ["@great_expectations"], "requirements": [], "has_full_test_suite": True, "manually_reviewed_code": True, } _library_metadata = library_metadata map_metric = "column_values.in_type_list" domain_keys: ClassVar[Tuple[str, ...]] = ( "column", "row_condition", "condition_parser", ) success_keys = ( "type_list", "mostly", ) args_keys = ( "column", "type_list", ) class Config: title = "Expect column values to be in type list" @staticmethod def schema_extra( schema: Dict[str, Any], model: Type[ExpectColumnValuesToBeInTypeList] ) -> None: ColumnMapExpectation.Config.schema_extra(schema, model) schema["properties"]["metadata"]["properties"].update( { "data_quality_issues": { "title": "Data Quality Issues", "type": "array", "const": DATA_QUALITY_ISSUES, }, "library_metadata": { "title": "Library Metadata", "type": "object", "const": model._library_metadata, }, "short_description": { "title": "Short Description", "type": "string", "const": EXPECTATION_SHORT_DESCRIPTION, }, "supported_data_sources": { "title": "Supported Data Sources", "type": "array", "const": SUPPORTED_DATA_SOURCES, }, } ) @classmethod @override def _prescriptive_template( cls, renderer_configuration: RendererConfiguration, ) -> RendererConfiguration: add_param_args: AddParamArgs = ( ("column", RendererValueType.STRING), ("type_list", RendererValueType.ARRAY), ("mostly", RendererValueType.NUMBER), ) for name, param_type in add_param_args: renderer_configuration.add_param(name=name, param_type=param_type) params = renderer_configuration.params if params.type_list: array_param_name = "type_list" param_prefix = "v__" renderer_configuration = cls._add_array_params( array_param_name=array_param_name, param_prefix=param_prefix, renderer_configuration=renderer_configuration, ) values_string: str = cls._get_array_string( array_param_name=array_param_name, param_prefix=param_prefix, renderer_configuration=renderer_configuration, ) if params.mostly and params.mostly.value < 1.0: renderer_configuration = cls._add_mostly_pct_param( renderer_configuration=renderer_configuration ) template_str = ( "value types must belong to this set: " + values_string + ", at least $mostly_pct % of the time." ) else: template_str = f"value types must belong to this set: {values_string}." else: template_str = "value types may be any value, but observed value will be reported" if renderer_configuration.include_column_name: template_str = f"$column {template_str}" renderer_configuration.template_str = template_str return renderer_configuration @classmethod @override @renderer(renderer_type=LegacyRendererType.PRESCRIPTIVE) @render_suite_parameter_string def _prescriptive_renderer( # noqa: C901, PLR0912 cls, configuration: Optional[ExpectationConfiguration] = None, result: Optional[ExpectationValidationResult] = None, runtime_configuration: Optional[dict] = None, **kwargs, ): runtime_configuration = runtime_configuration or {} include_column_name = runtime_configuration.get("include_column_name") is not False styling = runtime_configuration.get("styling") params = substitute_none_for_missing( configuration.kwargs if configuration else {}, ["column", "type_list", "mostly", "row_condition", "condition_parser"], ) if params["type_list"] is not None: for i, v in enumerate(params["type_list"]): params[f"v__{i!s}"] = v values_string = " ".join([f"$v__{i!s}" for i, v in enumerate(params["type_list"])]) if params["mostly"] is not None: if isinstance(params["mostly"], (int, float)) and params["mostly"] < 1.0: params["mostly_pct"] = num_to_str(params["mostly"] * 100, no_scientific=True) # params["mostly_pct"] = "{:.14f}".format(params["mostly"]*100).rstrip("0").rstrip(".") # noqa: E501 # FIXME CoP if include_column_name: template_str = ( "$column value types must belong to this set: " + values_string + ", at least $mostly_pct % of the time." ) else: template_str = ( "value types must belong to this set: " + values_string + ", at least $mostly_pct % of the time." ) else: # noqa: PLR5501 # FIXME CoP if include_column_name: template_str = f"$column value types must belong to this set: {values_string}." else: template_str = f"value types must belong to this set: {values_string}." else: # noqa: PLR5501 # FIXME CoP if include_column_name: template_str = ( "$column value types may be any value, but observed value will be reported" ) else: template_str = "value types may be any value, but observed value will be reported" if params["row_condition"] is not None: conditional_template_str = parse_row_condition_string(params["row_condition"]) template_str, styling = _style_row_condition( conditional_template_str, template_str, params, styling, ) return [ RenderedStringTemplateContent( content_block_type="string_template", string_template={ "template": template_str, "params": params, "styling": styling, }, ) ] def _validate_pandas( # noqa: C901, PLR0912 # FIXME CoP self, actual_column_type, expected_types_list, ): if expected_types_list is None: success = True else: comp_types = [] for type_ in expected_types_list: try: comp_types.append(np.dtype(type_).type) comp_types.append(np.dtype(type_)) except TypeError: try: pd_type = getattr(pd, type_) except AttributeError: pass else: if isinstance(pd_type, type): comp_types.append(pd_type) try: if isinstance(pd_type(), pd.core.dtypes.base.ExtensionDtype): comp_types.append(pd_type()) except TypeError: pass try: pd_type = getattr(pd.core.dtypes.dtypes, type_) if isinstance(pd_type, type): comp_types.append(pd_type) except AttributeError: pass native_type = _native_type_type_map(type_) if native_type is not None: comp_types.extend(native_type) # TODO: Remove when Numpy >=1.21 is pinned as a dependency _pandas_supports_extension_dtypes = version.parse(pd.__version__) >= version.parse( "0.24" ) _numpy_doesnt_support_extensions_properly = version.parse( np.__version__ ) < version.parse("1.21") if _numpy_doesnt_support_extensions_properly and _pandas_supports_extension_dtypes: # This works around a bug where Pandas nullable int types aren't compatible with Numpy dtypes # noqa: E501 # FIXME CoP # Note: Can't do set difference, the whole bugfix is because numpy types can't be compared to # noqa: E501 # FIXME CoP # ExtensionDtypes actual_type_is_ext_dtype = isinstance( actual_column_type, pd.core.dtypes.base.ExtensionDtype ) comp_types = { dtype for dtype in comp_types if isinstance(dtype, pd.core.dtypes.base.ExtensionDtype) == actual_type_is_ext_dtype } ### success = actual_column_type in comp_types return { "success": success, "result": {"observed_value": actual_column_type.type.__name__}, } def _validate_sqlalchemy(self, actual_column_type, expected_types_list, execution_engine): if expected_types_list is None: success = True elif execution_engine.dialect_name in [ GXSqlDialect.DATABRICKS, GXSqlDialect.POSTGRESQL, GXSqlDialect.SNOWFLAKE, GXSqlDialect.TRINO, ]: if isinstance(actual_column_type, str): success = any( actual_column_type.lower() == expected_type.lower() for expected_type in expected_types_list ) ret_type = actual_column_type else: ret_type = type(actual_column_type).__name__ success = any( ret_type.lower() == expected_type.lower() for expected_type in expected_types_list ) return { "success": success, "result": {"observed_value": ret_type}, } else: types = [] for type_ in expected_types_list: types.extend( _get_potential_sqlalchemy_types( execution_engine=execution_engine, expected_type=type_ ) ) success = isinstance(actual_column_type, tuple(types)) return { "success": success, "result": {"observed_value": type(actual_column_type).__name__}, } def _validate_spark( self, actual_column_type, expected_types_list, ): if expected_types_list is None: success = True else: types = [] for type_ in expected_types_list: try: type_class = getattr(pyspark.types, type_) types.append(type_class) except AttributeError: logger.debug(f"Unrecognized type: {type_}") if len(types) == 0: raise ValueError("No recognized spark types in expected_types_list") # noqa: TRY003 # FIXME CoP success = isinstance(actual_column_type, tuple(types)) return { "success": success, "result": {"observed_value": type(actual_column_type).__name__}, } @override def get_validation_dependencies( self, execution_engine: Optional[ExecutionEngine] = None, runtime_configuration: Optional[dict] = None, **kwargs, ) -> ValidationDependencies: from great_expectations.execution_engine import ( PandasExecutionEngine, ) # This calls BatchExpectation.get_validation_dependencies to set baseline validation_dependencies for the aggregate version # noqa: E501 # FIXME CoP # of the expectation. # We need to keep this as super(ColumnMapExpectation, self), which calls # BatchExpectation.get_validation_dependencies instead of ColumnMapExpectation.get_validation_dependencies. # noqa: E501 # FIXME CoP # This is because the map version of this expectation is only supported for Pandas, so we want the aggregate # noqa: E501 # FIXME CoP # version for the other backends. validation_dependencies: ValidationDependencies = super( ColumnMapExpectation, self ).get_validation_dependencies(execution_engine, runtime_configuration) configuration = self.configuration # Only PandasExecutionEngine supports the column map version of the expectation. if isinstance(execution_engine, PandasExecutionEngine): column_name = configuration.kwargs.get("column") if configuration else None expected_types_list = configuration.kwargs.get("type_list") if configuration else None metric_kwargs = get_metric_kwargs( metric_name="table.column_types", configuration=configuration, runtime_configuration=runtime_configuration, ) metric_domain_kwargs: dict = metric_kwargs.get("metric_domain_kwargs") or {} metric_value_kwargs = metric_kwargs.get("metric_value_kwargs") or {} table_column_types_configuration = MetricConfiguration( "table.column_types", metric_domain_kwargs=metric_domain_kwargs, metric_value_kwargs=metric_value_kwargs, ) actual_column_types_list = execution_engine.resolve_metrics( [table_column_types_configuration] )[table_column_types_configuration.id] try: actual_column_type = [ type_dict["type"] for type_dict in actual_column_types_list if type_dict["name"] == column_name ][0] except IndexError: actual_column_type = None # only use column map version if column dtype is object if ( actual_column_type and actual_column_type.type.__name__ == "object_" and expected_types_list is not None ): # this resets validation_dependencies using ColumnMapExpectation.get_validation_dependencies # noqa: E501 # FIXME CoP validation_dependencies = super().get_validation_dependencies( execution_engine, runtime_configuration ) # this adds table.column_types dependency for both aggregate and map versions of expectation column_types_metric_kwargs = get_metric_kwargs( metric_name="table.column_types", configuration=configuration, runtime_configuration=runtime_configuration, ) validation_dependencies.set_metric_configuration( metric_name="table.column_types", metric_configuration=MetricConfiguration( metric_name="table.column_types", metric_domain_kwargs=column_types_metric_kwargs["metric_domain_kwargs"], metric_value_kwargs=column_types_metric_kwargs["metric_value_kwargs"], ), ) return validation_dependencies @override def _validate( self, metrics: Dict, runtime_configuration: Optional[dict] = None, execution_engine: Optional[ExecutionEngine] = None, ): from great_expectations.execution_engine import ( PandasExecutionEngine, SparkDFExecutionEngine, SqlAlchemyExecutionEngine, ) configuration = self.configuration column_name = configuration.kwargs.get("column") expected_types_list = configuration.kwargs.get("type_list") actual_column_types_list = metrics.get("table.column_types") actual_column_type = ( [ type_dict["type"] for type_dict in actual_column_types_list if type_dict["name"] == column_name ][0] if actual_column_types_list else [] ) if isinstance(execution_engine, PandasExecutionEngine): # only PandasExecutionEngine supports map version of expectation and # only when column type is object if actual_column_type.type.__name__ == "object_" and expected_types_list is not None: # this calls ColumnMapMetric._validate return super()._validate(metrics, runtime_configuration, execution_engine) return self._validate_pandas( actual_column_type=actual_column_type, expected_types_list=expected_types_list, ) elif isinstance(execution_engine, SqlAlchemyExecutionEngine): return self._validate_sqlalchemy( actual_column_type=actual_column_type, expected_types_list=expected_types_list, execution_engine=execution_engine, ) elif isinstance(execution_engine, SparkDFExecutionEngine): return self._validate_spark( actual_column_type=actual_column_type, expected_types_list=expected_types_list, )
ExpectColumnValuesToBeInTypeList
python
pyparsing__pyparsing
examples/adventureEngine.py
{ "start": 5097, "end": 5740 }
class ____(Command): def __init__(self, quals): super().__init__("TAKE", "taking") self.subject = quals.item @staticmethod def help_description(): return "TAKE or PICKUP or PICK UP - pick up an object (but some are deadly)" def _do_command(self, player): rm = player.room subj = Item.items[self.subject] if subj in rm.inv and subj.isVisible: if subj.isTakeable: rm.remove_item(subj) player.take(subj) else: print(subj.cantTakeMessage) else: print(f"There is no {subj} here.")
TakeCommand
python
tensorflow__tensorflow
tensorflow/python/keras/engine/base_layer_utils.py
{ "start": 16303, "end": 18885 }
class ____(object): """Keeps track of properties currently inside a Layer/Model's `call`. Attributes: in_call: Whether currently inside the `call` of a Layer. layer: The `Layer` whose `call` is currently active. inputs: The inputs to the currently active `Layer`. build_graph: Whether currently inside a Graph or FuncGraph. training: Whether currently executing in training or inference mode. saving: Whether currently saving to SavedModel. frozen: Whether currently executing inside a `Layer` with `trainable` set to `False`. in_keras_graph: Whether executing inside the Keras Graph. """ def __init__(self): # Handle `in_call` separately as it is the most-read attr and reading it is # on the hot path. self.in_call = False self._state = { 'layer': None, 'inputs': None, 'build_graph': False, 'training': None, 'saving': None } # TODO(b/150169018): This logic can be replaced after the Functional API # refactor. self._in_keras_graph = False def enter(self, layer, inputs, build_graph, training, saving=None): """Push a Layer and its inputs and state onto the current call context. Args: layer: The `Layer` whose `call` is currently active. inputs: The inputs to the currently active `Layer`. build_graph: Whether currently inside a Graph or FuncGraph. training: Whether currently executing in training or inference mode. saving: Whether currently saving to SavedModel. Returns: Context manager. """ state = { 'layer': layer, 'inputs': inputs, 'build_graph': build_graph, 'training': training, 'saving': saving } return CallContextManager(self, state) @property def layer(self): return self._state['layer'] @property def inputs(self): return self._state['inputs'] @property def build_graph(self): return self._state['build_graph'] @property def training(self): return self._state['training'] @property def saving(self): return self._state['saving'] @property def frozen(self): layer = self._state['layer'] if not layer: return False return not layer.trainable @property def in_keras_graph(self): # Returns True even if in a subgraph of the Keras graph, such as those # created by control flow ops. if context.executing_eagerly(): return False return (self._in_keras_graph or getattr(backend.get_graph(), 'name', None) == 'keras_graph')
CallContext
python
python__mypy
mypy/errors.py
{ "start": 7957, "end": 10456 }
class ____: """An `IterationDependentErrors` instance serves to collect the `unreachable`, `redundant-expr`, and `redundant-casts` errors, as well as the revealed types, handled by the individual `IterationErrorWatcher` instances sequentially applied to the same code section.""" # One set of `unreachable`, `redundant-expr`, and `redundant-casts` errors per # iteration step. Meaning of the tuple items: ErrorCode, message, line, column, # end_line, end_column. uselessness_errors: list[set[tuple[ErrorCode, str, int, int, int, int]]] # One set of unreachable line numbers per iteration step. Not only the lines where # the error report occurs but really all unreachable lines. unreachable_lines: list[set[int]] # One list of revealed types for each `reveal_type` statement. Each created list # can grow during the iteration. Meaning of the tuple items: line, column, # end_line, end_column: revealed_types: dict[tuple[int, int, int | None, int | None], list[Type]] def __init__(self) -> None: self.uselessness_errors = [] self.unreachable_lines = [] self.revealed_types = defaultdict(list) def yield_uselessness_error_infos(self) -> Iterator[tuple[str, Context, ErrorCode]]: """Report only those `unreachable`, `redundant-expr`, and `redundant-casts` errors that could not be ruled out in any iteration step.""" persistent_uselessness_errors = set() for candidate in set(chain(*self.uselessness_errors)): if all( (candidate in errors) or (candidate[2] in lines) for errors, lines in zip(self.uselessness_errors, self.unreachable_lines) ): persistent_uselessness_errors.add(candidate) for error_info in persistent_uselessness_errors: context = Context(line=error_info[2], column=error_info[3]) context.end_line = error_info[4] context.end_column = error_info[5] yield error_info[1], context, error_info[0] def yield_revealed_type_infos(self) -> Iterator[tuple[list[Type], Context]]: """Yield all types revealed in at least one iteration step.""" for note_info, types in self.revealed_types.items(): context = Context(line=note_info[0], column=note_info[1]) context.end_line = note_info[2] context.end_column = note_info[3] yield types, context
IterationDependentErrors
python
airbytehq__airbyte
airbyte-integrations/connectors/source-iterable/source_iterable/streams.py
{ "start": 18280, "end": 18369 }
class ____(IterableExportEventsStreamAdjustableRange): data_field = "smsClick"
SmsClick
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pyflakes/F821_17.py
{ "start": 839, "end": 1164 }
class ____: ... # Type parameters do not escape function scopes from some_library import some_decorator @some_decorator(T) # F821: Undefined name `T` - not accessible in decorators def foo[T](t: T) -> None: ... T # F821: Undefined name `T` - not accessible afterward function scope # Type parameters in classes
ForwardB
python
bokeh__bokeh
src/bokeh/models/tools.py
{ "start": 66464, "end": 69318 }
class ____(EditTool, Drag, Tap): ''' *toolbar icon*: |box_edit_icon| Allows drawing, dragging and deleting box-like glyphs (e.g. ``Block``, ``Rect``, ``HStrip``) on one or more renderers by editing the underlying ``ColumnDataSource`` data. Like other drawing tools, the renderers that are to be edited must be supplied explicitly as a list. When drawing a new box the data will always be added to the ``ColumnDataSource`` on the first supplied renderer. The tool will modify the columns on the data source corresponding to the ``x``, ``y``, ``width`` and ``height`` values of the glyph. Any additional columns in the data source will be padded with ``empty_value``, when adding a new box. The supported actions include: * Add box: Hold shift then click and drag anywhere on the plot or press once to start drawing, move the mouse and press again to finish drawing. * Move box: Click and drag an existing box, the box will be dropped once you let go of the mouse button. * Delete box: Tap a box to select it then press BACKSPACE key while the mouse is within the plot area. To **Move** or **Delete** multiple boxes at once: * Move selection: Select box(es) with SHIFT+tap (or another selection tool) then drag anywhere on the plot. Selecting and then dragging on a specific box will move both. * Delete selection: Select box(es) with SHIFT+tap (or another selection tool) then press BACKSPACE while the mouse is within the plot area. .. |box_edit_icon| image:: /_images/icons/box-edit.svg :height: 24px :alt: Icon of a solid line box with a plus sign in the lower right representing the box-edit tool in the toolbar. ''' # explicit __init__ to support Init signatures def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) renderers = List(GlyphRendererOf(LRTBGlyph, Rect, HStrip, VStrip), help=""" A list of renderers corresponding to glyphs that may be edited. """) dimensions = Enum(Dimensions, default="both", help=""" Which dimensions the box drawing is to be free in. By default, users may freely draw boxes with any dimensions. If only "width" is set, the box will be constrained to span the entire vertical space of the plot, only the horizontal dimension can be controlled. If only "height" is set, the box will be constrained to span the entire horizontal space of the plot, and the vertical dimension can be controlled. """) num_objects = Int(default=0, help=""" Defines a limit on the number of boxes that can be drawn. By default there is no limit on the number of objects, but if enabled the oldest drawn box will be dropped to make space for the new box being added. """)
BoxEditTool
python
spyder-ide__spyder
external-deps/spyder-remote-services/spyder_remote_services/services/files/compression.py
{ "start": 281, "end": 571 }
class ____(enum.Enum): ZIP_64 = enum.auto() ZIP_32 = enum.auto() NO_COMPRESSION_BUFFERED_32 = enum.auto() NO_COMPRESSION_BUFFERED_64 = enum.auto() NO_COMPRESSION_STREAMED_32 = enum.auto() NO_COMPRESSION_STREAMED_64 = enum.auto() @dataclass(frozen=True)
CompressionType
python
scipy__scipy
scipy/stats/_discrete_distns.py
{ "start": 63174, "end": 66095 }
class ____(_nchypergeom_gen): r"""A Wallenius' noncentral hypergeometric discrete random variable. Wallenius' noncentral hypergeometric distribution models drawing objects of two types from a bin. `M` is the total number of objects, `n` is the number of Type I objects, and `odds` is the odds ratio: the odds of selecting a Type I object rather than a Type II object when there is only one object of each type. The random variate represents the number of Type I objects drawn if we draw a pre-determined `N` objects from a bin one by one. %(before_notes)s See Also -------- nchypergeom_fisher, hypergeom, nhypergeom Notes ----- Let mathematical symbols :math:`N`, :math:`n`, and :math:`M` correspond with parameters `N`, `n`, and `M` (respectively) as defined above. The probability mass function is defined as .. math:: p(x; N, n, M) = \binom{n}{x} \binom{M - n}{N-x} \int_0^1 \left(1-t^{\omega/D}\right)^x\left(1-t^{1/D}\right)^{N-x} dt for :math:`x \in [x_l, x_u]`, :math:`M \in {\mathbb N}`, :math:`n \in [0, M]`, :math:`N \in [0, M]`, :math:`\omega > 0`, where :math:`x_l = \max(0, N - (M - n))`, :math:`x_u = \min(N, n)`, .. math:: D = \omega(n - x) + ((M - n)-(N-x)), and the binomial coefficients are defined as .. math:: \binom{n}{k} \equiv \frac{n!}{k! (n - k)!}. `nchypergeom_wallenius` uses the BiasedUrn package by Agner Fog with permission for it to be distributed under SciPy's license. The symbols used to denote the shape parameters (`N`, `n`, and `M`) are not universally accepted; they are chosen for consistency with `hypergeom`. Note that Wallenius' noncentral hypergeometric distribution is distinct from Fisher's noncentral hypergeometric distribution, which models take a handful of objects from the bin at once, finding out afterwards that `N` objects were taken. When the odds ratio is unity, however, both distributions reduce to the ordinary hypergeometric distribution. %(after_notes)s References ---------- .. [1] Agner Fog, "Biased Urn Theory". https://cran.r-project.org/web/packages/BiasedUrn/vignettes/UrnTheory.pdf .. [2] "Wallenius' noncentral hypergeometric distribution", Wikipedia, https://en.wikipedia.org/wiki/Wallenius'_noncentral_hypergeometric_distribution %(example)s """ rvs_name = "rvs_wallenius" dist = _PyWalleniusNCHypergeometric nchypergeom_wallenius = nchypergeom_wallenius_gen( name='nchypergeom_wallenius', longname="A Wallenius' noncentral hypergeometric") # Collect names of classes and objects in this module. pairs = list(globals().copy().items()) _distn_names, _distn_gen_names = get_distribution_names(pairs, rv_discrete) __all__ = _distn_names + _distn_gen_names
nchypergeom_wallenius_gen
python
pytest-dev__pytest
doc/en/example/assertion/failure_demo.py
{ "start": 331, "end": 646 }
class ____: def test_simple(self): def f(): return 42 def g(): return 43 assert f() == g() def test_simple_multiline(self): otherfunc_multi(42, 6 * 9) def test_not(self): def f(): return 42 assert not f()
TestFailing
python
pypa__pipenv
pipenv/vendor/tomlkit/parser.py
{ "start": 2449, "end": 38523 }
class ____: """ Parser for TOML documents. """ def __init__(self, string: str | bytes) -> None: # Input to parse self._src = Source(decode(string)) self._aot_stack: list[Key] = [] @property def _state(self): return self._src.state @property def _idx(self): return self._src.idx @property def _current(self): return self._src.current @property def _marker(self): return self._src.marker def extract(self) -> str: """ Extracts the value between marker and index """ return self._src.extract() def inc(self, exception: type[ParseError] | None = None) -> bool: """ Increments the parser if the end of the input has not been reached. Returns whether or not it was able to advance. """ return self._src.inc(exception=exception) def inc_n(self, n: int, exception: type[ParseError] | None = None) -> bool: """ Increments the parser by n characters if the end of the input has not been reached. """ return self._src.inc_n(n=n, exception=exception) def consume(self, chars, min=0, max=-1): """ Consume chars until min/max is satisfied is valid. """ return self._src.consume(chars=chars, min=min, max=max) def end(self) -> bool: """ Returns True if the parser has reached the end of the input. """ return self._src.end() def mark(self) -> None: """ Sets the marker to the index's current position """ self._src.mark() def parse_error(self, exception=ParseError, *args, **kwargs): """ Creates a generic "parse error" at the current position. """ return self._src.parse_error(exception, *args, **kwargs) def parse(self) -> TOMLDocument: body = TOMLDocument(True) # Take all keyvals outside of tables/AoT's. while not self.end(): # Break out if a table is found if self._current == "[": break # Otherwise, take and append one KV item = self._parse_item() if not item: break key, value = item if (key is not None and key.is_multi()) or not self._merge_ws(value, body): # We actually have a table try: body.append(key, value) except Exception as e: raise self.parse_error(ParseError, str(e)) from e self.mark() while not self.end(): key, value = self._parse_table() if isinstance(value, Table) and value.is_aot_element(): # This is just the first table in an AoT. Parse the rest of the array # along with it. value = self._parse_aot(value, key) try: body.append(key, value) except Exception as e: raise self.parse_error(ParseError, str(e)) from e body.parsing(False) return body def _merge_ws(self, item: Item, container: Container) -> bool: """ Merges the given Item with the last one currently in the given Container if both are whitespace items. Returns True if the items were merged. """ last = container.last_item() if not last: return False if not isinstance(item, Whitespace) or not isinstance(last, Whitespace): return False start = self._idx - (len(last.s) + len(item.s)) container.body[-1] = ( container.body[-1][0], Whitespace(self._src[start : self._idx]), ) return True def _is_child(self, parent: Key, child: Key) -> bool: """ Returns whether a key is strictly a child of another key. AoT siblings are not considered children of one another. """ parent_parts = tuple(parent) child_parts = tuple(child) if parent_parts == child_parts: return False return parent_parts == child_parts[: len(parent_parts)] def _parse_item(self) -> tuple[Key | None, Item] | None: """ Attempts to parse the next item and returns it, along with its key if the item is value-like. """ self.mark() with self._state as state: while True: c = self._current if c == "\n": # Found a newline; Return all whitespace found up to this point. self.inc() return None, Whitespace(self.extract()) elif c in " \t\r": # Skip whitespace. if not self.inc(): return None, Whitespace(self.extract()) elif c == "#": # Found a comment, parse it indent = self.extract() cws, comment, trail = self._parse_comment_trail() return None, Comment(Trivia(indent, cws, comment, trail)) elif c == "[": # Found a table, delegate to the calling function. return else: # Beginning of a KV pair. # Return to beginning of whitespace so it gets included # as indentation for the KV about to be parsed. state.restore = True break return self._parse_key_value(True) def _parse_comment_trail(self, parse_trail: bool = True) -> tuple[str, str, str]: """ Returns (comment_ws, comment, trail) If there is no comment, comment_ws and comment will simply be empty. """ if self.end(): return "", "", "" comment = "" comment_ws = "" self.mark() while True: c = self._current if c == "\n": break elif c == "#": comment_ws = self.extract() self.mark() self.inc() # Skip # # The comment itself while not self.end() and not self._current.is_nl(): code = ord(self._current) if code == CHR_DEL or code <= CTRL_CHAR_LIMIT and code != CTRL_I: raise self.parse_error(InvalidControlChar, code, "comments") if not self.inc(): break comment = self.extract() self.mark() break elif c in " \t\r": self.inc() else: raise self.parse_error(UnexpectedCharError, c) if self.end(): break trail = "" if parse_trail: while self._current.is_spaces() and self.inc(): pass if self._current == "\r": self.inc() if self._current == "\n": self.inc() if self._idx != self._marker or self._current.is_ws(): trail = self.extract() return comment_ws, comment, trail def _parse_key_value(self, parse_comment: bool = False) -> tuple[Key, Item]: # Leading indent self.mark() while self._current.is_spaces() and self.inc(): pass indent = self.extract() # Key key = self._parse_key() self.mark() found_equals = self._current == "=" while self._current.is_kv_sep() and self.inc(): if self._current == "=": if found_equals: raise self.parse_error(UnexpectedCharError, "=") else: found_equals = True if not found_equals: raise self.parse_error(UnexpectedCharError, self._current) if not key.sep: key.sep = self.extract() else: key.sep += self.extract() # Value val = self._parse_value() # Comment if parse_comment: cws, comment, trail = self._parse_comment_trail() meta = val.trivia if not meta.comment_ws: meta.comment_ws = cws meta.comment = comment meta.trail = trail else: val.trivia.trail = "" val.trivia.indent = indent return key, val def _parse_key(self) -> Key: """ Parses a Key at the current position; WS before the key must be exhausted first at the callsite. """ self.mark() while self._current.is_spaces() and self.inc(): # Skip any leading whitespace pass if self._current in "\"'": return self._parse_quoted_key() else: return self._parse_bare_key() def _parse_quoted_key(self) -> Key: """ Parses a key enclosed in either single or double quotes. """ # Extract the leading whitespace original = self.extract() quote_style = self._current key_type = next((t for t in KeyType if t.value == quote_style), None) if key_type is None: raise RuntimeError("Should not have entered _parse_quoted_key()") key_str = self._parse_string( StringType.SLB if key_type == KeyType.Basic else StringType.SLL ) if key_str._t.is_multiline(): raise self.parse_error(UnexpectedCharError, key_str._t.value) original += key_str.as_string() self.mark() while self._current.is_spaces() and self.inc(): pass original += self.extract() key = SingleKey(str(key_str), t=key_type, sep="", original=original) if self._current == ".": self.inc() key = key.concat(self._parse_key()) return key def _parse_bare_key(self) -> Key: """ Parses a bare key. """ while ( self._current.is_bare_key_char() or self._current.is_spaces() ) and self.inc(): pass original = self.extract() key = original.strip() if not key: # Empty key raise self.parse_error(EmptyKeyError) if " " in key: # Bare key with spaces in it raise self.parse_error(ParseError, f'Invalid key "{key}"') key = SingleKey(key, KeyType.Bare, "", original) if self._current == ".": self.inc() key = key.concat(self._parse_key()) return key def _parse_value(self) -> Item: """ Attempts to parse a value at the current position. """ self.mark() c = self._current trivia = Trivia() if c == StringType.SLB.value: return self._parse_basic_string() elif c == StringType.SLL.value: return self._parse_literal_string() elif c == BoolType.TRUE.value[0]: return self._parse_true() elif c == BoolType.FALSE.value[0]: return self._parse_false() elif c == "[": return self._parse_array() elif c == "{": return self._parse_inline_table() elif c in "+-" or self._peek(4) in { "+inf", "-inf", "inf", "+nan", "-nan", "nan", }: # Number while self._current not in " \t\n\r#,]}" and self.inc(): pass raw = self.extract() item = self._parse_number(raw, trivia) if item is not None: return item raise self.parse_error(InvalidNumberError) elif c in string.digits: # Integer, Float, Date, Time or DateTime while self._current not in " \t\n\r#,]}" and self.inc(): pass raw = self.extract() m = RFC_3339_LOOSE.match(raw) if m: if m.group(1) and m.group(5): # datetime try: dt = parse_rfc3339(raw) assert isinstance(dt, datetime.datetime) return DateTime( dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.microsecond, dt.tzinfo, trivia, raw, ) except ValueError: raise self.parse_error(InvalidDateTimeError) from None if m.group(1): try: dt = parse_rfc3339(raw) assert isinstance(dt, datetime.date) date = Date(dt.year, dt.month, dt.day, trivia, raw) self.mark() while self._current not in "\t\n\r#,]}" and self.inc(): pass time_raw = self.extract() time_part = time_raw.rstrip() trivia.comment_ws = time_raw[len(time_part) :] if not time_part: return date dt = parse_rfc3339(raw + time_part) assert isinstance(dt, datetime.datetime) return DateTime( dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.microsecond, dt.tzinfo, trivia, raw + time_part, ) except ValueError: raise self.parse_error(InvalidDateError) from None if m.group(5): try: t = parse_rfc3339(raw) assert isinstance(t, datetime.time) return Time( t.hour, t.minute, t.second, t.microsecond, t.tzinfo, trivia, raw, ) except ValueError: raise self.parse_error(InvalidTimeError) from None item = self._parse_number(raw, trivia) if item is not None: return item raise self.parse_error(InvalidNumberError) else: raise self.parse_error(UnexpectedCharError, c) def _parse_true(self): return self._parse_bool(BoolType.TRUE) def _parse_false(self): return self._parse_bool(BoolType.FALSE) def _parse_bool(self, style: BoolType) -> Bool: with self._state: style = BoolType(style) # only keep parsing for bool if the characters match the style # try consuming rest of chars in style for c in style: self.consume(c, min=1, max=1) return Bool(style, Trivia()) def _parse_array(self) -> Array: # Consume opening bracket, EOF here is an issue (middle of array) self.inc(exception=UnexpectedEofError) elems: list[Item] = [] prev_value = None while True: # consume whitespace mark = self._idx self.consume(TOMLChar.SPACES + TOMLChar.NL) indent = self._src[mark : self._idx] newline = set(TOMLChar.NL) & set(indent) if newline: elems.append(Whitespace(indent)) continue # consume comment if self._current == "#": cws, comment, trail = self._parse_comment_trail(parse_trail=False) elems.append(Comment(Trivia(indent, cws, comment, trail))) continue # consume indent if indent: elems.append(Whitespace(indent)) continue # consume value if not prev_value: try: elems.append(self._parse_value()) prev_value = True continue except UnexpectedCharError: pass # consume comma if prev_value and self._current == ",": self.inc(exception=UnexpectedEofError) elems.append(Whitespace(",")) prev_value = False continue # consume closing bracket if self._current == "]": # consume closing bracket, EOF here doesn't matter self.inc() break raise self.parse_error(UnexpectedCharError, self._current) try: res = Array(elems, Trivia()) except ValueError: pass else: return res def _parse_inline_table(self) -> InlineTable: # consume opening bracket, EOF here is an issue (middle of array) self.inc(exception=UnexpectedEofError) elems = Container(True) trailing_comma = None while True: # consume leading whitespace mark = self._idx self.consume(TOMLChar.SPACES) raw = self._src[mark : self._idx] if raw: elems.add(Whitespace(raw)) if not trailing_comma: # None: empty inline table # False: previous key-value pair was not followed by a comma if self._current == "}": # consume closing bracket, EOF here doesn't matter self.inc() break if ( trailing_comma is False or trailing_comma is None and self._current == "," ): # Either the previous key-value pair was not followed by a comma # or the table has an unexpected leading comma. raise self.parse_error(UnexpectedCharError, self._current) else: # True: previous key-value pair was followed by a comma if self._current == "}" or self._current == ",": raise self.parse_error(UnexpectedCharError, self._current) key, val = self._parse_key_value(False) elems.add(key, val) # consume trailing whitespace mark = self._idx self.consume(TOMLChar.SPACES) raw = self._src[mark : self._idx] if raw: elems.add(Whitespace(raw)) # consume trailing comma trailing_comma = self._current == "," if trailing_comma: # consume closing bracket, EOF here is an issue (middle of inline table) self.inc(exception=UnexpectedEofError) return InlineTable(elems, Trivia()) def _parse_number(self, raw: str, trivia: Trivia) -> Item | None: # Leading zeros are not allowed sign = "" if raw.startswith(("+", "-")): sign = raw[0] raw = raw[1:] if len(raw) > 1 and ( raw.startswith("0") and not raw.startswith(("0.", "0o", "0x", "0b", "0e")) or sign and raw.startswith(".") ): return None if raw.startswith(("0o", "0x", "0b")) and sign: return None digits = "[0-9]" base = 10 if raw.startswith("0b"): digits = "[01]" base = 2 elif raw.startswith("0o"): digits = "[0-7]" base = 8 elif raw.startswith("0x"): digits = "[0-9a-f]" base = 16 # Underscores should be surrounded by digits clean = re.sub(f"(?i)(?<={digits})_(?={digits})", "", raw).lower() if "_" in clean: return None if ( clean.endswith(".") or not clean.startswith("0x") and clean.split("e", 1)[0].endswith(".") ): return None try: return Integer(int(sign + clean, base), trivia, sign + raw) except ValueError: try: return Float(float(sign + clean), trivia, sign + raw) except ValueError: return None def _parse_literal_string(self) -> String: with self._state: return self._parse_string(StringType.SLL) def _parse_basic_string(self) -> String: with self._state: return self._parse_string(StringType.SLB) def _parse_escaped_char(self, multiline): if multiline and self._current.is_ws(): # When the last non-whitespace character on a line is # a \, it will be trimmed along with all whitespace # (including newlines) up to the next non-whitespace # character or closing delimiter. # """\ # hello \ # world""" tmp = "" while self._current.is_ws(): tmp += self._current # consume the whitespace, EOF here is an issue # (middle of string) self.inc(exception=UnexpectedEofError) continue # the escape followed by whitespace must have a newline # before any other chars if "\n" not in tmp: raise self.parse_error(InvalidCharInStringError, self._current) return "" if self._current in _escaped: c = _escaped[self._current] # consume this char, EOF here is an issue (middle of string) self.inc(exception=UnexpectedEofError) return c if self._current in {"u", "U"}: # this needs to be a unicode u, ue = self._peek_unicode(self._current == "U") if u is not None: # consume the U char and the unicode value self.inc_n(len(ue) + 1) return u raise self.parse_error(InvalidUnicodeValueError) raise self.parse_error(InvalidCharInStringError, self._current) def _parse_string(self, delim: StringType) -> String: # only keep parsing for string if the current character matches the delim if self._current != delim.unit: raise self.parse_error( InternalParserError, f"Invalid character for string type {delim}", ) # consume the opening/first delim, EOF here is an issue # (middle of string or middle of delim) self.inc(exception=UnexpectedEofError) if self._current == delim.unit: # consume the closing/second delim, we do not care if EOF occurs as # that would simply imply an empty single line string if not self.inc() or self._current != delim.unit: # Empty string return String(delim, "", "", Trivia()) # consume the third delim, EOF here is an issue (middle of string) self.inc(exception=UnexpectedEofError) delim = delim.toggle() # convert delim to multi delim self.mark() # to extract the original string with whitespace and all value = "" # A newline immediately following the opening delimiter will be trimmed. if delim.is_multiline(): if self._current == "\n": # consume the newline, EOF here is an issue (middle of string) self.inc(exception=UnexpectedEofError) else: cur = self._current with self._state(restore=True): if self.inc(): cur += self._current if cur == "\r\n": self.inc_n(2, exception=UnexpectedEofError) escaped = False # whether the previous key was ESCAPE while True: code = ord(self._current) if ( delim.is_singleline() and not escaped and (code == CHR_DEL or code <= CTRL_CHAR_LIMIT and code != CTRL_I) ) or ( delim.is_multiline() and not escaped and ( code == CHR_DEL or code <= CTRL_CHAR_LIMIT and code not in [CTRL_I, CTRL_J, CTRL_M] ) ): raise self.parse_error(InvalidControlChar, code, "strings") elif not escaped and self._current == delim.unit: # try to process current as a closing delim original = self.extract() close = "" if delim.is_multiline(): # Consume the delimiters to see if we are at the end of the string close = "" while self._current == delim.unit: close += self._current self.inc() if len(close) < 3: # Not a triple quote, leave in result as-is. # Adding back the characters we already consumed value += close continue if len(close) == 3: # We are at the end of the string return String(delim, value, original, Trivia()) if len(close) >= 6: raise self.parse_error(InvalidCharInStringError, self._current) value += close[:-3] original += close[:-3] return String(delim, value, original, Trivia()) else: # consume the closing delim, we do not care if EOF occurs as # that would simply imply the end of self._src self.inc() return String(delim, value, original, Trivia()) elif delim.is_basic() and escaped: # attempt to parse the current char as an escaped value, an exception # is raised if this fails value += self._parse_escaped_char(delim.is_multiline()) # no longer escaped escaped = False elif delim.is_basic() and self._current == "\\": # the next char is being escaped escaped = True # consume this char, EOF here is an issue (middle of string) self.inc(exception=UnexpectedEofError) else: # this is either a literal string where we keep everything as is, # or this is not a special escaped char in a basic string value += self._current # consume this char, EOF here is an issue (middle of string) self.inc(exception=UnexpectedEofError) def _parse_table( self, parent_name: Key | None = None, parent: Table | None = None ) -> tuple[Key, Table | AoT]: """ Parses a table element. """ if self._current != "[": raise self.parse_error( InternalParserError, "_parse_table() called on non-bracket character." ) indent = self.extract() self.inc() # Skip opening bracket if self.end(): raise self.parse_error(UnexpectedEofError) is_aot = False if self._current == "[": if not self.inc(): raise self.parse_error(UnexpectedEofError) is_aot = True try: key = self._parse_key() except EmptyKeyError: raise self.parse_error(EmptyTableNameError) from None if self.end(): raise self.parse_error(UnexpectedEofError) elif self._current != "]": raise self.parse_error(UnexpectedCharError, self._current) key.sep = "" full_key = key name_parts = tuple(key) if any(" " in part.key.strip() and part.is_bare() for part in name_parts): raise self.parse_error( ParseError, f'Invalid table name "{full_key.as_string()}"' ) missing_table = False if parent_name: parent_name_parts = tuple(parent_name) else: parent_name_parts = () if len(name_parts) > len(parent_name_parts) + 1: missing_table = True name_parts = name_parts[len(parent_name_parts) :] values = Container(True) self.inc() # Skip closing bracket if is_aot: # TODO: Verify close bracket self.inc() cws, comment, trail = self._parse_comment_trail() result = Null() table = Table( values, Trivia(indent, cws, comment, trail), is_aot, name=name_parts[0].key if name_parts else key.key, display_name=full_key.as_string(), is_super_table=False, ) if len(name_parts) > 1: if missing_table: # Missing super table # i.e. a table initialized like this: [foo.bar] # without initializing [foo] # # So we have to create the parent tables table = Table( Container(True), Trivia("", cws, comment, trail), is_aot and name_parts[0] in self._aot_stack, is_super_table=True, name=name_parts[0].key, ) result = table key = name_parts[0] for i, _name in enumerate(name_parts[1:]): child = table.get( _name, Table( Container(True), Trivia(indent, cws, comment, trail), is_aot and i == len(name_parts) - 2, is_super_table=i < len(name_parts) - 2, name=_name.key, display_name=( full_key.as_string() if i == len(name_parts) - 2 else None ), ), ) if is_aot and i == len(name_parts) - 2: table.raw_append(_name, AoT([child], name=table.name, parsed=True)) else: table.raw_append(_name, child) table = child values = table.value else: if name_parts: key = name_parts[0] while not self.end(): item = self._parse_item() if item: _key, item = item if not self._merge_ws(item, values): table.raw_append(_key, item) else: if self._current == "[": _, key_next = self._peek_table() if self._is_child(full_key, key_next): key_next, table_next = self._parse_table(full_key, table) table.raw_append(key_next, table_next) # Picking up any sibling while not self.end(): _, key_next = self._peek_table() if not self._is_child(full_key, key_next): break key_next, table_next = self._parse_table(full_key, table) table.raw_append(key_next, table_next) break else: raise self.parse_error( InternalParserError, "_parse_item() returned None on a non-bracket character.", ) table.value._validate_out_of_order_table() if isinstance(result, Null): result = table if is_aot and (not self._aot_stack or full_key != self._aot_stack[-1]): result = self._parse_aot(result, full_key) return key, result def _peek_table(self) -> tuple[bool, Key]: """ Peeks ahead non-intrusively by cloning then restoring the initial state of the parser. Returns the name of the table about to be parsed, as well as whether it is part of an AoT. """ # we always want to restore after exiting this scope with self._state(save_marker=True, restore=True): if self._current != "[": raise self.parse_error( InternalParserError, "_peek_table() entered on non-bracket character", ) # AoT self.inc() is_aot = False if self._current == "[": self.inc() is_aot = True try: return is_aot, self._parse_key() except EmptyKeyError: raise self.parse_error(EmptyTableNameError) from None def _parse_aot(self, first: Table, name_first: Key) -> AoT: """ Parses all siblings of the provided table first and bundles them into an AoT. """ payload = [first] self._aot_stack.append(name_first) while not self.end(): is_aot_next, name_next = self._peek_table() if is_aot_next and name_next == name_first: _, table = self._parse_table(name_first) payload.append(table) else: break self._aot_stack.pop() return AoT(payload, parsed=True) def _peek(self, n: int) -> str: """ Peeks ahead n characters. n is the max number of characters that will be peeked. """ # we always want to restore after exiting this scope with self._state(restore=True): buf = "" for _ in range(n): if self._current not in " \t\n\r#,]}" + self._src.EOF: buf += self._current self.inc() continue break return buf def _peek_unicode(self, is_long: bool) -> tuple[str | None, str | None]: """ Peeks ahead non-intrusively by cloning then restoring the initial state of the parser. Returns the unicode value is it's a valid one else None. """ # we always want to restore after exiting this scope with self._state(save_marker=True, restore=True): if self._current not in {"u", "U"}: raise self.parse_error( InternalParserError, "_peek_unicode() entered on non-unicode value" ) self.inc() # Dropping prefix self.mark() if is_long: chars = 8 else: chars = 4 if not self.inc_n(chars): value, extracted = None, None else: extracted = self.extract() if extracted[0].lower() == "d" and extracted[1].strip("01234567"): return None, None try: value = chr(int(extracted, 16)) except (ValueError, OverflowError): value = None return value, extracted
Parser
python
gevent__gevent
src/greentest/3.14/test_urllib2.py
{ "start": 1021, "end": 2752 }
class ____(unittest.TestCase): def test___all__(self): # Verify which names are exposed for module in 'request', 'response', 'parse', 'error', 'robotparser': context = {} exec('from urllib.%s import *' % module, context) del context['__builtins__'] for k, v in context.items(): self.assertEqual(v.__module__, 'urllib.%s' % module, "%r is exposed in 'urllib.%s' but defined in %r" % (k, module, v.__module__)) def test_trivial(self): # A couple trivial tests # clear _opener global variable self.addCleanup(urllib.request.urlcleanup) self.assertRaises(ValueError, urllib.request.urlopen, 'bogus url') # XXX Name hacking to get this to work on Windows. fname = os.path.abspath(urllib.request.__file__).replace(os.sep, '/') if os.name == 'nt': file_url = "file:///%s" % fname else: file_url = "file://%s" % fname with urllib.request.urlopen(file_url) as f: f.read() def test_parse_http_list(self): tests = [ ('a,b,c', ['a', 'b', 'c']), ('path"o,l"og"i"cal, example', ['path"o,l"og"i"cal', 'example']), ('a, b, "c", "d", "e,f", g, h', ['a', 'b', '"c"', '"d"', '"e,f"', 'g', 'h']), ('a="b\\"c", d="e\\,f", g="h\\\\i"', ['a="b"c"', 'd="e,f"', 'g="h\\i"'])] for string, list in tests: self.assertEqual(urllib.request.parse_http_list(string), list) def test_URLError_reasonstr(self): err = urllib.error.URLError('reason') self.assertIn(err.reason, str(err))
TrivialTests
python
tox-dev__tox
src/tox/tox_env/python/pip/req/args.py
{ "start": 3322, "end": 3801 }
class ____(Action): def __call__( self, parser: ArgumentParser, # noqa: ARG002 namespace: Namespace, values: str | Sequence[Any] | None, option_string: str | None = None, # noqa: ARG002 ) -> None: if getattr(namespace, self.dest, None) is None: setattr(namespace, self.dest, []) current = getattr(namespace, self.dest) if values not in current: current.append(values)
AddUniqueAction
python
PyCQA__pylint
tests/functional/i/invalid/invalid_length/invalid_length_hint_returned.py
{ "start": 600, "end": 676 }
class ____: """LengthHintgth through the metaclass."""
ThirdGoodLengthHint
python
huggingface__transformers
src/transformers/cache_utils.py
{ "start": 9539, "end": 14942 }
class ____(CacheLayerMixin): """ A static cache layer that stores the key and value states as static tensors of shape `[batch_size, num_heads, max_cache_len), head_dim]`. It lazily allocates its full backing tensors, and then mutates them in-place. Built for `torch.compile` support. Args: max_cache_len (`int`): Maximum number of tokens that can be stored, used for tensor preallocation. """ is_compileable = True is_sliding = False def __init__(self, max_cache_len: int): super().__init__() self.max_cache_len = max_cache_len def lazy_initialization(self, key_states: torch.Tensor): """ Lazy initialization of the keys and values tensors. This allows to get all properties (dtype, device, num_heads in case of TP etc...) at runtime directly, which is extremely practical as it avoids moving devices, dtypes etc later on for each `update` (which could break the static dynamo addresses as well). If this is unwanted, one can call `early_initialization(...)` on the Cache directly, which will call this function ahead-of-time (this is required for `torch.export` for example). Note that for `compile`, as we internally don't compile the prefill, this is guaranteed to have been called already when compiling. If compiling the prefill as well, e.g. calling `model.compile(...)` before `generate` with a static cache, it is still supported in general, but without guarantees depending on the compilation options (e.g. cuda graphs, i.e. `mode="reduce-overhead"` is known to fail). But it will in general work correctly, and prefill should not be compiled anyway for performances! """ self.max_batch_size, self.num_heads, _, self.head_dim = key_states.shape self.dtype, self.device = key_states.dtype, key_states.device self.keys = torch.zeros( (self.max_batch_size, self.num_heads, self.max_cache_len, self.head_dim), dtype=self.dtype, device=self.device, ) self.values = torch.zeros( (self.max_batch_size, self.num_heads, self.max_cache_len, self.head_dim), dtype=self.dtype, device=self.device, ) # Note: `mark_static_address` is used to tag the cache as a fixed data pointer, preventing compiled graph # breaks when updating the cache. However, it is not supported when tracing the graph, so we skip it in this case. # As prefill should never be compiled, this is not an issue and it will still be run (except when users compile # prefill explicitly, but this should be avoided!) if not is_torchdynamo_compiling(): torch._dynamo.mark_static_address(self.keys) torch._dynamo.mark_static_address(self.values) self.is_initialized = True def update( self, key_states: torch.Tensor, value_states: torch.Tensor, cache_kwargs: Optional[dict[str, Any]] = None, ) -> tuple[torch.Tensor, torch.Tensor]: """ Update the key and value caches in-place, and return the necessary keys and value states. Args: key_states (`torch.Tensor`): The new key states to cache. value_states (`torch.Tensor`): The new value states to cache. cache_kwargs (`dict[str, Any]`, *optional*): Additional arguments for the cache. Returns: tuple[`torch.Tensor`, `torch.Tensor`]: The key and value states. """ # Lazy initialization if not self.is_initialized: self.lazy_initialization(key_states) # Some old models give None for `cache_position` or even omit passing `cache_kwargs` when used as cross-attention, # in which case we should copy the whole Layer (key_states.shape[-2] == self.max_cache_len) cache_position = cache_kwargs.get("cache_position") if cache_kwargs is not None else None cache_position = ( cache_position if cache_position is not None else torch.arange(key_states.shape[-2], device=self.device) ) # Update the cache try: self.keys.index_copy_(2, cache_position, key_states) self.values.index_copy_(2, cache_position, value_states) except NotImplementedError: # Fallback for devices like MPS where index_copy_ might not be supported. self.keys[:, :, cache_position] = key_states self.values[:, :, cache_position] = value_states return self.keys, self.values def get_mask_sizes(self, cache_position: torch.Tensor) -> tuple[int, int]: """Return the length and offset of the cache, used to generate the attention mask""" kv_offset = 0 kv_length = self.max_cache_len return kv_length, kv_offset def get_seq_length(self) -> int: """Returns the sequence length of the cached states.""" # Occupied cache == any slot in the 3rd dim (sequence length) holds a non-zero value. To save on compute, let's # limit the check to the first batch member and head dimension. return (self.keys[0, 0].any(dim=-1)).sum() if self.is_initialized else 0 def get_max_cache_shape(self) -> int: """Return the maximum cache shape of the cache""" return self.max_cache_len
StaticLayer
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/sensors/emr.py
{ "start": 15663, "end": 20421 }
class ____(EmrBaseSensor): """ Poll the EMR JobFlow Cluster until it reaches any of the target states; raise AirflowException on failure. With the default target states, sensor waits cluster to be terminated. When target_states is set to ['RUNNING', 'WAITING'] sensor waits until job flow to be ready (after 'STARTING' and 'BOOTSTRAPPING' states) .. seealso:: For more information on how to use this sensor, take a look at the guide: :ref:`howto/sensor:EmrJobFlowSensor` :param job_flow_id: job_flow_id to check the state of :param target_states: the target states, sensor waits until job flow reaches any of these states. In deferrable mode it would run until reach the terminal state. :param failed_states: the failure states, sensor fails when job flow reaches any of these states :param max_attempts: Maximum number of tries before failing :param deferrable: Run sensor in the deferrable mode. """ template_fields: Sequence[str] = aws_template_fields("job_flow_id", "target_states", "failed_states") template_ext: Sequence[str] = () operator_extra_links = ( EmrClusterLink(), EmrLogsLink(), ) def __init__( self, *, job_flow_id: str, target_states: Iterable[str] | None = None, failed_states: Iterable[str] | None = None, max_attempts: int = 60, deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False), **kwargs, ): super().__init__(**kwargs) self.job_flow_id = job_flow_id self.target_states = target_states or ["TERMINATED"] self.failed_states = failed_states or ["TERMINATED_WITH_ERRORS"] self.max_attempts = max_attempts self.deferrable = deferrable def get_emr_response(self, context: Context) -> dict[str, Any]: """ Make an API call with boto3 and get cluster-level details. .. seealso:: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/emr.html#EMR.Client.describe_cluster :return: response """ self.log.info("Poking cluster %s", self.job_flow_id) response = self.hook.conn.describe_cluster(ClusterId=self.job_flow_id) EmrClusterLink.persist( context=context, operator=self, region_name=self.hook.conn_region_name, aws_partition=self.hook.conn_partition, job_flow_id=self.job_flow_id, ) EmrLogsLink.persist( context=context, operator=self, region_name=self.hook.conn_region_name, aws_partition=self.hook.conn_partition, job_flow_id=self.job_flow_id, log_uri=get_log_uri(cluster=response), ) return response @staticmethod def state_from_response(response: dict[str, Any]) -> str: """ Get state from response dictionary. :param response: response from AWS API :return: current state of the cluster """ return response["Cluster"]["Status"]["State"] @staticmethod def failure_message_from_response(response: dict[str, Any]) -> str | None: """ Get failure message from response dictionary. :param response: response from AWS API :return: failure message """ cluster_status = response["Cluster"]["Status"] state_change_reason = cluster_status.get("StateChangeReason") if state_change_reason: return ( f"for code: {state_change_reason.get('Code', 'No code')} " f"with message {state_change_reason.get('Message', 'Unknown')}" ) return None def execute(self, context: Context) -> None: if not self.deferrable: super().execute(context=context) elif not self.poke(context): self.defer( timeout=timedelta(seconds=self.poke_interval * self.max_attempts), trigger=EmrTerminateJobFlowTrigger( job_flow_id=self.job_flow_id, waiter_max_attempts=self.max_attempts, aws_conn_id=self.aws_conn_id, waiter_delay=int(self.poke_interval), ), method_name="execute_complete", ) def execute_complete(self, context: Context, event: dict[str, Any] | None = None) -> None: validated_event = validate_execute_complete_event(event) if validated_event["status"] != "success": raise AirflowException(f"Error while running job: {validated_event}") self.log.info("Job completed.")
EmrJobFlowSensor
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 260865, "end": 261460 }
class ____(sgqlc.types.Input): """A collaborator to update on a project. Only one of the userId or teamId should be provided. """ __schema__ = github_schema __field_names__ = ("user_id", "team_id", "role") user_id = sgqlc.types.Field(ID, graphql_name="userId") """The ID of the user as a collaborator.""" team_id = sgqlc.types.Field(ID, graphql_name="teamId") """The ID of the team as a collaborator.""" role = sgqlc.types.Field(sgqlc.types.non_null(ProjectV2Roles), graphql_name="role") """The role to grant the collaborator"""
ProjectV2Collaborator
python
pandas-dev__pandas
pandas/core/indexes/extension.py
{ "start": 4927, "end": 5365 }
class ____(ExtensionIndex): """ Index subclass for indexes backed by NDArrayBackedExtensionArray. """ _data: NDArrayBackedExtensionArray def _get_engine_target(self) -> np.ndarray: return self._data._ndarray def _from_join_target(self, result: np.ndarray) -> ArrayLike: assert result.dtype == self._data._ndarray.dtype return self._data._from_backing_data(result)
NDArrayBackedExtensionIndex
python
astropy__astropy
astropy/time/core.py
{ "start": 14422, "end": 16481 }
class ____(TimeInfoBase): """ Container for meta information like name, description, format. This is required when the object is used as a mixin column within a table, but can be used as a general way to store meta information. """ _represent_as_dict_extra_attrs = ("format", "scale") def new_like(self, cols, length, metadata_conflicts="warn", name=None): """ Return a new TimeDelta instance which is consistent with the input Time objects ``cols`` and has ``length`` rows. This is intended for creating an empty Time instance whose elements can be set in-place for table operations like join or vstack. It checks that the input locations and attributes are consistent. This is used when a Time object is used as a mixin column in an astropy Table. Parameters ---------- cols : list List of input columns (Time objects) length : int Length of the output column object metadata_conflicts : str ('warn'|'error'|'silent') How to handle metadata conflicts name : str Output column name Returns ------- col : Time (or subclass) Empty instance of this class consistent with ``cols`` """ # Get merged info attributes like shape, dtype, format, description, etc. attrs = self.merge_cols_attributes( cols, metadata_conflicts, name, ("meta", "description") ) attrs.pop("dtype") # Not relevant for Time col0 = cols[0] # Make a new Time object with the desired shape and attributes shape = (length,) + attrs.pop("shape") jd1 = np.zeros(shape, dtype="f8") jd2 = np.zeros(shape, dtype="f8") out = self._parent_cls(jd1, jd2, format="jd", scale=col0.scale) out.format = col0.format # Set remaining info attributes for attr, value in attrs.items(): setattr(out.info, attr, value) return out
TimeDeltaInfo
python
getsentry__sentry
src/sentry/sentry_apps/logic.py
{ "start": 4035, "end": 15421 }
class ____: sentry_app: SentryApp name: str | None = None author: str | None = None status: str | None = None scopes: list[str] | None = None events: list[str] | None = None webhook_url: str | None = None redirect_url: str | None = None is_alertable: bool | None = None verify_install: bool | None = None schema: Schema | None = None overview: str | None = None allowed_origins: list[str] | None = None popularity: int | None = None features: list[int] | None = None def run(self, user: User | RpcUser) -> SentryApp: with SentryAppInteractionEvent( operation_type=SentryAppInteractionType.MANAGEMENT, event_type=SentryAppEventType.APP_UPDATE, ).capture(): with transaction.atomic(router.db_for_write(User)): self._update_name() self._update_author() self._update_features(user=user) self._update_status(user=user) self._update_scopes() self._update_events() self._update_webhook_url() self._update_redirect_url() self._update_is_alertable() self._update_verify_install() self._update_overview() self._update_allowed_origins() new_schema_elements = self._update_schema() self._update_popularity(user=user) self.sentry_app.save() self._update_service_hooks() self.record_analytics(user, new_schema_elements) return self.sentry_app def _update_features(self, user: User | RpcUser) -> None: if self.features is not None: if not _is_elevated_user(user) and self.sentry_app.status == SentryAppStatus.PUBLISHED: raise ParseError(detail="Cannot update features on a published integration.") IntegrationFeature.objects.clean_update( incoming_features=self.features, target=self.sentry_app, target_type=IntegrationTypes.SENTRY_APP, ) def _update_name(self) -> None: if self.name is not None: self.sentry_app.name = self.name def _update_author(self) -> None: if self.author is not None: self.sentry_app.author = self.author def _update_status(self, user: User | RpcUser) -> None: if self.status is not None: if _is_elevated_user(user): if self.status == SentryAppStatus.PUBLISHED_STR: self.sentry_app.status = SentryAppStatus.PUBLISHED self.sentry_app.date_published = timezone.now() if self.status == SentryAppStatus.UNPUBLISHED_STR: self.sentry_app.status = SentryAppStatus.UNPUBLISHED if self.status == SentryAppStatus.PUBLISH_REQUEST_INPROGRESS_STR: self.sentry_app.status = SentryAppStatus.PUBLISH_REQUEST_INPROGRESS def _update_scopes(self) -> None: if self.scopes is not None: if self.sentry_app.status == SentryAppStatus.PUBLISHED and set( self.sentry_app.scope_list ) != set(self.scopes): raise ParseError(detail="Cannot update permissions on a published integration.") # We are using a pre_save signal to enforce scope hierarchy on the ApiToken model. # Because we're using bulk_update here to update all the tokens for the SentryApp, # we need to manually enforce the hierarchy because the pre_save signal won't be called. self.scopes = add_scope_hierarchy(self.scopes) self.sentry_app.scope_list = self.scopes # update the scopes of active tokens tokens tokens = list( ApiToken.objects.filter( Q(expires_at__isnull=True) | Q(expires_at__gt=timezone.now()), application=self.sentry_app.application, ) ) for token in tokens: token.scope_list = self.scopes ApiToken.objects.bulk_update(tokens, ["scope_list"]) def _update_events(self) -> None: if self.events is not None: for event in self.events: needed_scope = REQUIRED_EVENT_PERMISSIONS[event] if needed_scope not in self.sentry_app.scope_list: raise ParseError( detail=f"{event} webhooks require the {needed_scope} permission." ) self.sentry_app.events = expand_events(self.events) def _update_service_hooks(self) -> None: organization_context = organization_service.get_organization_by_id( id=self.sentry_app.owner_id ) assert organization_context is not None, "Organization cannot be None for ff" if features.has( "organizations:service-hooks-outbox", organization_context.organization, ): self._update_service_hooks_via_outbox() else: self._update_service_hooks_via_task() def _update_service_hooks_via_outbox(self) -> None: if installations := SentryAppInstallation.objects.filter(sentry_app_id=self.sentry_app.id): org_ids_and_region_names = OrganizationMapping.objects.filter( organization_id__in=installations.values_list("organization_id", flat=True) ).values_list("organization_id", "region_name") installation_org_id_to_region_name = { org_id: region_name for org_id, region_name in org_ids_and_region_names } with outbox_context( transaction.atomic(router.db_for_write(ControlOutbox)), flush=False ): for installation in installations: assert ( installation_org_id_to_region_name.get(installation.organization_id) is not None ), f"OrganizationMapping must exist for installation {installation.id} and organization {installation.organization_id}" ControlOutbox( shard_scope=OutboxScope.APP_SCOPE, shard_identifier=self.sentry_app.id, object_identifier=installation.id, category=OutboxCategory.SERVICE_HOOK_UPDATE, region_name=installation_org_id_to_region_name[ installation.organization_id ], ).save() logger.info( "_update_service_hooks_via_outbox.created_outbox_entry", extra={ "installation_id": installation.id, "sentry_app_id": self.sentry_app.id, "events": self.sentry_app.events, "application_id": self.sentry_app.application_id, "region_name": installation_org_id_to_region_name[ installation.organization_id ], }, ) def _update_service_hooks_via_task(self) -> None: if self.sentry_app.is_published: # if it's a published integration, we need to do many updates so we have to do it in a task so we don't time out # the client won't know it succeeds but there's not much we can do about that unfortunately create_or_update_service_hooks_for_sentry_app.apply_async( kwargs={ "sentry_app_id": self.sentry_app.id, "webhook_url": self.sentry_app.webhook_url, "events": self.sentry_app.events, } ) return # for unpublished integrations that aren't installed yet, we may not have an installation # if we don't, then won't have any service hooks try: installation = SentryAppInstallation.objects.get(sentry_app_id=self.sentry_app.id) except SentryAppInstallation.DoesNotExist: return create_or_update_service_hooks_for_installation( installation=installation, webhook_url=self.sentry_app.webhook_url, events=self.sentry_app.events, ) def _update_webhook_url(self) -> None: if self.webhook_url is not None: self.sentry_app.webhook_url = self.webhook_url def _update_redirect_url(self) -> None: if self.redirect_url is not None: self.sentry_app.redirect_url = self.redirect_url def _update_is_alertable(self) -> None: if self.is_alertable is not None: self.sentry_app.is_alertable = self.is_alertable def _update_verify_install(self) -> None: if self.verify_install is not None: if self.sentry_app.is_internal and self.verify_install: raise ParseError(detail="Internal integrations cannot have verify_install=True.") self.sentry_app.verify_install = self.verify_install def _update_overview(self) -> None: if self.overview is not None: self.sentry_app.overview = self.overview def _update_allowed_origins(self) -> None: if self.allowed_origins and self.sentry_app.application: self.sentry_app.application.allowed_origins = "\n".join(self.allowed_origins) self.sentry_app.application.save() def _update_popularity(self, user: User | RpcUser) -> None: if self.popularity is not None: if _is_elevated_user(user): self.sentry_app.popularity = self.popularity def _update_schema(self) -> set[str] | None: if self.schema is not None: self.sentry_app.schema = self.schema new_schema_elements = self._get_new_schema_elements() self._delete_old_ui_components() self._create_ui_components() return new_schema_elements return None def _get_new_schema_elements(self) -> set[str]: current = SentryAppComponent.objects.filter(sentry_app=self.sentry_app).values_list( "type", flat=True ) return _get_schema_types(self.schema) - set(current) def _delete_old_ui_components(self) -> None: SentryAppComponent.objects.filter(sentry_app_id=self.sentry_app.id).delete() def _create_ui_components(self) -> None: if self.schema is not None: for element in self.schema.get("elements", []): SentryAppComponent.objects.create( type=element["type"], sentry_app_id=self.sentry_app.id, schema=element ) def record_analytics(self, user: User | RpcUser, new_schema_elements: set[str] | None) -> None: created_alert_rule_ui_component = "alert-rule-action" in (new_schema_elements or set()) analytics.record( SentryAppUpdatedEvent( user_id=user.id, organization_id=self.sentry_app.owner_id, sentry_app=self.sentry_app.slug, created_alert_rule_ui_component=created_alert_rule_ui_component, ) ) @dataclasses.dataclass
SentryAppUpdater
python
chardet__chardet
chardet/metadata/languages.py
{ "start": 320, "end": 12470 }
class ____: """Metadata about a language useful for training models :ivar name: The human name for the language, in English. :type name: str :ivar iso_code: 2-letter ISO 639-1 if possible, 3-letter ISO code otherwise, or use another catalog as a last resort. :type iso_code: str :ivar use_ascii: Whether or not ASCII letters should be included in trained models. :type use_ascii: bool :ivar charsets: The charsets we want to support and create data for. :type charsets: list of str :ivar alphabet: The characters in the language's alphabet. If `use_ascii` is `True`, you only need to add those not in the ASCII set. :type alphabet: str :ivar wiki_start_pages: The Wikipedia pages to start from if we're crawling Wikipedia for training data. :type wiki_start_pages: list of str """ def __init__( self, name: Optional[str] = None, iso_code: Optional[str] = None, use_ascii: bool = True, charsets: Optional[List[str]] = None, alphabet: Optional[str] = None, wiki_start_pages: Optional[List[str]] = None, ) -> None: super().__init__() self.name = name self.iso_code = iso_code self.use_ascii = use_ascii self.charsets = charsets if self.use_ascii: if alphabet: alphabet += ascii_letters else: alphabet = ascii_letters elif not alphabet: raise ValueError("Must supply alphabet if use_ascii is False") self.alphabet = "".join(sorted(set(alphabet))) if alphabet else None self.wiki_start_pages = wiki_start_pages def __repr__(self) -> str: param_str = ", ".join( f"{k}={v!r}" for k, v in self.__dict__.items() if not k.startswith("_") ) return f"{self.__class__.__name__}({param_str})" LANGUAGES = { "Arabic": Language( name="Arabic", iso_code="ar", use_ascii=False, # We only support encodings that use isolated # forms, because the current recommendation is # that the rendering system handles presentation # forms. This means we purposefully skip IBM864. charsets=["ISO-8859-6", "WINDOWS-1256", "CP720", "CP864"], alphabet="ءآأؤإئابةتثجحخدذرزسشصضطظعغػؼؽؾؿـفقكلمنهوىيًٌٍَُِّ", wiki_start_pages=["الصفحة_الرئيسية"], ), "Belarusian": Language( name="Belarusian", iso_code="be", use_ascii=False, charsets=["ISO-8859-5", "WINDOWS-1251", "IBM866", "MacCyrillic"], alphabet="АБВГДЕЁЖЗІЙКЛМНОПРСТУЎФХЦЧШЫЬЭЮЯабвгдеёжзійклмнопрстуўфхцчшыьэюяʼ", wiki_start_pages=["Галоўная_старонка"], ), "Bulgarian": Language( name="Bulgarian", iso_code="bg", use_ascii=False, charsets=["ISO-8859-5", "WINDOWS-1251", "IBM855"], alphabet="АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЬЮЯабвгдежзийклмнопрстуфхцчшщъьюя", wiki_start_pages=["Начална_страница"], ), "Czech": Language( name="Czech", iso_code="cz", use_ascii=True, charsets=["ISO-8859-2", "WINDOWS-1250"], alphabet="áčďéěíňóřšťúůýžÁČĎÉĚÍŇÓŘŠŤÚŮÝŽ", wiki_start_pages=["Hlavní_strana"], ), "Danish": Language( name="Danish", iso_code="da", use_ascii=True, charsets=["ISO-8859-1", "ISO-8859-15", "WINDOWS-1252", "MacRoman"], alphabet="æøåÆØÅ", wiki_start_pages=["Forside"], ), "German": Language( name="German", iso_code="de", use_ascii=True, charsets=["ISO-8859-1", "ISO-8859-15", "WINDOWS-1252", "MacRoman"], alphabet="äöüßẞÄÖÜ", wiki_start_pages=["Wikipedia:Hauptseite"], ), "Greek": Language( name="Greek", iso_code="el", use_ascii=False, charsets=["ISO-8859-7", "WINDOWS-1253"], alphabet="αβγδεζηθικλμνξοπρσςτυφχψωάέήίόύώΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΣΤΥΦΧΨΩΆΈΉΊΌΎΏ", wiki_start_pages=["Πύλη:Κύρια"], ), "English": Language( name="English", iso_code="en", use_ascii=True, charsets=["ISO-8859-1", "WINDOWS-1252", "MacRoman"], wiki_start_pages=["Main_Page"], ), "Esperanto": Language( name="Esperanto", iso_code="eo", # Q, W, X, and Y not used at all use_ascii=False, charsets=["ISO-8859-3"], alphabet="abcĉdefgĝhĥijĵklmnoprsŝtuŭvzABCĈDEFGĜHĤIJĴKLMNOPRSŜTUŬVZ", wiki_start_pages=["Vikipedio:Ĉefpaĝo"], ), "Spanish": Language( name="Spanish", iso_code="es", use_ascii=True, charsets=["ISO-8859-1", "ISO-8859-15", "WINDOWS-1252", "MacRoman"], alphabet="ñáéíóúüÑÁÉÍÓÚÜ", wiki_start_pages=["Wikipedia:Portada"], ), "Estonian": Language( name="Estonian", iso_code="et", use_ascii=False, charsets=["ISO-8859-4", "ISO-8859-13", "WINDOWS-1257"], # C, F, Š, Q, W, X, Y, Z, Ž are only for # loanwords alphabet="ABDEGHIJKLMNOPRSTUVÕÄÖÜabdeghijklmnoprstuvõäöü", wiki_start_pages=["Esileht"], ), "Finnish": Language( name="Finnish", iso_code="fi", use_ascii=True, charsets=["ISO-8859-1", "ISO-8859-15", "WINDOWS-1252", "MacRoman"], alphabet="ÅÄÖŠŽåäöšž", wiki_start_pages=["Wikipedia:Etusivu"], ), "French": Language( name="French", iso_code="fr", use_ascii=True, charsets=["ISO-8859-1", "ISO-8859-15", "WINDOWS-1252", "MacRoman"], alphabet="œàâçèéîïùûêŒÀÂÇÈÉÎÏÙÛÊ", wiki_start_pages=["Wikipédia:Accueil_principal", "Bœuf (animal)"], ), "Hebrew": Language( name="Hebrew", iso_code="he", use_ascii=False, charsets=["ISO-8859-8", "WINDOWS-1255"], alphabet="אבגדהוזחטיךכלםמןנסעףפץצקרשתװױײ", wiki_start_pages=["עמוד_ראשי"], ), "Croatian": Language( name="Croatian", iso_code="hr", # Q, W, X, Y are only used for foreign words. use_ascii=False, charsets=["ISO-8859-2", "WINDOWS-1250"], alphabet="abcčćdđefghijklmnoprsštuvzžABCČĆDĐEFGHIJKLMNOPRSŠTUVZŽ", wiki_start_pages=["Glavna_stranica"], ), "Hungarian": Language( name="Hungarian", iso_code="hu", # Q, W, X, Y are only used for foreign words. use_ascii=False, charsets=["ISO-8859-2", "WINDOWS-1250"], alphabet="abcdefghijklmnoprstuvzáéíóöőúüűABCDEFGHIJKLMNOPRSTUVZÁÉÍÓÖŐÚÜŰ", wiki_start_pages=["Kezdőlap"], ), "Italian": Language( name="Italian", iso_code="it", use_ascii=True, charsets=["ISO-8859-1", "ISO-8859-15", "WINDOWS-1252", "MacRoman"], alphabet="ÀÈÉÌÒÓÙàèéìòóù", wiki_start_pages=["Pagina_principale"], ), "Lithuanian": Language( name="Lithuanian", iso_code="lt", use_ascii=False, charsets=["ISO-8859-13", "WINDOWS-1257", "ISO-8859-4"], # Q, W, and X not used at all alphabet="AĄBCČDEĘĖFGHIĮYJKLMNOPRSŠTUŲŪVZŽaąbcčdeęėfghiįyjklmnoprsštuųūvzž", wiki_start_pages=["Pagrindinis_puslapis"], ), "Latvian": Language( name="Latvian", iso_code="lv", use_ascii=False, charsets=["ISO-8859-13", "WINDOWS-1257", "ISO-8859-4"], # Q, W, X, Y are only for loanwords alphabet="AĀBCČDEĒFGĢHIĪJKĶLĻMNŅOPRSŠTUŪVZŽaābcčdeēfgģhiījkķlļmnņoprsštuūvzž", wiki_start_pages=["Sākumlapa"], ), "Macedonian": Language( name="Macedonian", iso_code="mk", use_ascii=False, charsets=["ISO-8859-5", "WINDOWS-1251", "MacCyrillic", "IBM855"], alphabet="АБВГДЃЕЖЗЅИЈКЛЉМНЊОПРСТЌУФХЦЧЏШабвгдѓежзѕијклљмнњопрстќуфхцчџш", wiki_start_pages=["Главна_страница"], ), "Dutch": Language( name="Dutch", iso_code="nl", use_ascii=True, charsets=["ISO-8859-1", "WINDOWS-1252", "MacRoman"], wiki_start_pages=["Hoofdpagina"], ), "Polish": Language( name="Polish", iso_code="pl", # Q and X are only used for foreign words. use_ascii=False, charsets=["ISO-8859-2", "WINDOWS-1250"], alphabet="AĄBCĆDEĘFGHIJKLŁMNŃOÓPRSŚTUWYZŹŻaąbcćdeęfghijklłmnńoóprsśtuwyzźż", wiki_start_pages=["Wikipedia:Strona_główna"], ), "Portuguese": Language( name="Portuguese", iso_code="pt", use_ascii=True, charsets=["ISO-8859-1", "ISO-8859-15", "WINDOWS-1252", "MacRoman"], alphabet="ÁÂÃÀÇÉÊÍÓÔÕÚáâãàçéêíóôõú", wiki_start_pages=["Wikipédia:Página_principal"], ), "Romanian": Language( name="Romanian", iso_code="ro", use_ascii=True, charsets=["ISO-8859-2", "WINDOWS-1250"], alphabet="ăâîșțĂÂÎȘȚ", wiki_start_pages=["Pagina_principală"], ), "Russian": Language( name="Russian", iso_code="ru", use_ascii=False, charsets=[ "ISO-8859-5", "WINDOWS-1251", "KOI8-R", "MacCyrillic", "IBM866", "IBM855", ], alphabet="абвгдеёжзийклмнопрстуфхцчшщъыьэюяАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ", wiki_start_pages=["Заглавная_страница"], ), "Slovak": Language( name="Slovak", iso_code="sk", use_ascii=True, charsets=["ISO-8859-2", "WINDOWS-1250"], alphabet="áäčďéíĺľňóôŕšťúýžÁÄČĎÉÍĹĽŇÓÔŔŠŤÚÝŽ", wiki_start_pages=["Hlavná_stránka"], ), "Slovene": Language( name="Slovene", iso_code="sl", # Q, W, X, Y are only used for foreign words. use_ascii=False, charsets=["ISO-8859-2", "WINDOWS-1250"], alphabet="abcčdefghijklmnoprsštuvzžABCČDEFGHIJKLMNOPRSŠTUVZŽ", wiki_start_pages=["Glavna_stran"], ), # Serbian can be written in both Latin and Cyrillic, but there's no # simple way to get the Latin alphabet pages from Wikipedia through # the API, so for now we just support Cyrillic. "Serbian": Language( name="Serbian", iso_code="sr", alphabet="АБВГДЂЕЖЗИЈКЛЉМНЊОПРСТЋУФХЦЧЏШабвгдђежзијклљмнњопрстћуфхцчџш", charsets=["ISO-8859-5", "WINDOWS-1251", "MacCyrillic", "IBM855"], wiki_start_pages=["Главна_страна"], ), "Thai": Language( name="Thai", iso_code="th", use_ascii=False, charsets=["ISO-8859-11", "TIS-620", "CP874"], alphabet="กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛", wiki_start_pages=["หน้าหลัก"], ), "Turkish": Language( name="Turkish", iso_code="tr", # Q, W, and X are not used by Turkish use_ascii=False, charsets=["ISO-8859-3", "ISO-8859-9", "WINDOWS-1254"], alphabet="abcçdefgğhıijklmnoöprsştuüvyzâîûABCÇDEFGĞHIİJKLMNOÖPRSŞTUÜVYZÂÎÛ", wiki_start_pages=["Ana_Sayfa"], ), "Vietnamese": Language( name="Vietnamese", iso_code="vi", use_ascii=False, # Windows-1258 is the only common 8-bit # Vietnamese encoding supported by Python. # From Wikipedia: # For systems that lack support for Unicode, # dozens of 8-bit Vietnamese code pages are # available.[1] The most common are VISCII # (TCVN 5712:1993), VPS, and Windows-1258.[3] # Where ASCII is required, such as when # ensuring readability in plain text e-mail, # Vietnamese letters are often encoded # according to Vietnamese Quoted-Readable # (VIQR) or VSCII Mnemonic (VSCII-MNEM),[4] # though usage of either variable-width # scheme has declined dramatically following # the adoption of Unicode on the World Wide # Web. charsets=["WINDOWS-1258"], alphabet="aăâbcdđeêghiklmnoôơpqrstuưvxyAĂÂBCDĐEÊGHIKLMNOÔƠPQRSTUƯVXY", wiki_start_pages=["Chữ_Quốc_ngữ"], ), }
Language
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typedDictClosed3.py
{ "start": 1625, "end": 1691 }
class ____(ParentClosed4): b: ReadOnly[int | str]
ChildClosed4_5
python
huggingface__transformers
src/transformers/models/vit_mae/modeling_vit_mae.py
{ "start": 11729, "end": 14637 }
class ____(nn.Module): """ This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial `hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a Transformer. """ def __init__(self, config): super().__init__() image_size, patch_size = config.image_size, config.patch_size num_channels, hidden_size = config.num_channels, config.hidden_size image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size) patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size) num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.image_size = image_size self.patch_size = patch_size self.num_channels = num_channels self.num_patches = num_patches self.projection = nn.Conv2d(num_channels, hidden_size, kernel_size=patch_size, stride=patch_size) def forward(self, pixel_values, interpolate_pos_encoding: bool = False): batch_size, num_channels, height, width = pixel_values.shape if num_channels != self.num_channels: raise ValueError( "Make sure that the channel dimension of the pixel values match with the one set in the configuration." ) if not interpolate_pos_encoding and (height != self.image_size[0] or width != self.image_size[1]): raise ValueError( f"Input image size ({height}*{width}) doesn't match model ({self.image_size[0]}*{self.image_size[1]})." ) x = self.projection(pixel_values).flatten(2).transpose(1, 2) return x # Copied from transformers.models.bert.modeling_bert.eager_attention_forward def eager_attention_forward( module: nn.Module, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, attention_mask: Optional[torch.Tensor], scaling: Optional[float] = None, dropout: float = 0.0, **kwargs: Unpack[TransformersKwargs], ): if scaling is None: scaling = query.size(-1) ** -0.5 # Take the dot product between "query" and "key" to get the raw attention scores. attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling if attention_mask is not None: attention_mask = attention_mask[:, :, :, : key.shape[-2]] attn_weights = attn_weights + attention_mask attn_weights = nn.functional.softmax(attn_weights, dim=-1) attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training) attn_output = torch.matmul(attn_weights, value) attn_output = attn_output.transpose(1, 2).contiguous() return attn_output, attn_weights # Copied from transformers.models.vit.modeling_vit.ViTSelfAttention ViT->ViTMAE
ViTMAEPatchEmbeddings
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 302547, "end": 303043 }
class ____(sgqlc.types.Input): """Ordering options for sponsorship newsletter connections.""" __schema__ = github_schema __field_names__ = ("field", "direction") field = sgqlc.types.Field(sgqlc.types.non_null(SponsorshipNewsletterOrderField), graphql_name="field") """The field to order sponsorship newsletters by.""" direction = sgqlc.types.Field(sgqlc.types.non_null(OrderDirection), graphql_name="direction") """The ordering direction."""
SponsorshipNewsletterOrder
python
astropy__astropy
astropy/samp/tests/web_profile_test_helpers.py
{ "start": 373, "end": 739 }
class ____(WebProfileDialog): def __init__(self): self.polling = True WebProfileDialog.__init__(self) def show_dialog(self, *args): self.consent() def poll(self): while self.polling: self.handle_queue() time.sleep(0.1) def stop(self): self.polling = False
AlwaysApproveWebProfileDialog
python
wandb__wandb
wandb/util.py
{ "start": 25571, "end": 25995 }
class ____(json.JSONEncoder): """A JSON Encoder that handles some extra types. This encoder turns numpy like objects with a size > 32 into histograms. """ def default(self, obj: Any) -> Any: obj, converted = json_friendly(obj) obj, compressed = maybe_compress_history(obj) if converted: return obj return json.JSONEncoder.default(self, obj)
WandBHistoryJSONEncoder
python
huggingface__transformers
tests/models/aya_vision/test_modeling_aya_vision.py
{ "start": 7104, "end": 19831 }
class ____(unittest.TestCase): @classmethod def setUpClass(cls): cls.model_checkpoint = "CohereForAI/aya-vision-8b" cls.model = None @classmethod def tearDownClass(cls): del cls.model cleanup(torch_device, gc_collect=True) def tearDown(self): cleanup(torch_device, gc_collect=True) @classmethod def get_model(cls): # Use 4-bit on T4 device_type, major, _ = get_device_properties() load_in_4bit = (device_type == "cuda") and (major < 8) dtype = None if load_in_4bit else torch.float16 if load_in_4bit: quantization_config = BitsAndBytesConfig(load_in_4bit=True) else: quantization_config = None if cls.model is None: cls.model = AyaVisionForConditionalGeneration.from_pretrained( cls.model_checkpoint, device_map=torch_device, dtype=dtype, quantization_config=quantization_config ) return cls.model @slow @require_torch_accelerator def test_small_model_integration_forward(self): processor = AutoProcessor.from_pretrained(self.model_checkpoint) model = self.get_model() messages = [ { "role": "user", "content": [ {"type": "image", "url": "http://images.cocodataset.org/val2017/000000039769.jpg"}, {"type": "text", "text": "Please describe the image explicitly."}, ], } ] inputs = processor.apply_chat_template( messages, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt" ).to(torch_device, dtype=torch.float16) # Forward with torch.inference_mode(): output = model(**inputs) actual_logits = output.logits[0, -1, :5].cpu() EXPECTED_LOGITS = Expectations( { ("xpu", 3): [1.6699, 0.6260, 3.2266, 8.5547, 2.209], # 4-bit ("cuda", 7): [0.1097, 0.3481, 3.8340, 9.7969, 2.0488], ("cuda", 8): [1.6396, 0.6094, 3.1992, 8.5234, 2.1875], } ) # fmt: skip expected_logits = torch.tensor(EXPECTED_LOGITS.get_expectation(), dtype=torch.float16) self.assertTrue( torch.allclose(actual_logits, expected_logits, atol=0.1), f"Actual logits: {actual_logits}" f"\nExpected logits: {expected_logits}" f"\nDifference: {torch.abs(actual_logits - expected_logits)}", ) @slow @require_torch_accelerator @require_deterministic_for_xpu def test_small_model_integration_generate_text_only(self): processor = AutoProcessor.from_pretrained(self.model_checkpoint) model = self.get_model() messages = [ { "role": "user", "content": [ {"type": "text", "text": "Write a haiku"}, ], } ] inputs = processor.apply_chat_template( messages, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt" ).to(torch_device, dtype=torch.float16) with torch.no_grad(): generate_ids = model.generate(**inputs, max_new_tokens=25, do_sample=False) decoded_output = processor.decode( generate_ids[0, inputs["input_ids"].shape[1] :], skip_special_tokens=True ) expected_outputs = Expectations( { ("xpu", 3): "Whispers on the breeze,\nLeaves dance under moonlit sky,\nNature's quiet song.", # 4-bit ("cuda", 7): "Sure, here's a haiku for you:\n\nMorning dew sparkles,\nPetals unfold in sunlight,\n", ("cuda", 8): "Whispers on the breeze,\nLeaves dance under moonlit skies,\nNature's quiet song.", } ) # fmt: skip expected_output = expected_outputs.get_expectation() self.assertEqual(decoded_output, expected_output) @slow @require_torch_accelerator @require_deterministic_for_xpu def test_small_model_integration_generate_chat_template(self): processor = AutoProcessor.from_pretrained(self.model_checkpoint) model = self.get_model() messages = [ { "role": "user", "content": [ {"type": "image", "url": "http://images.cocodataset.org/val2017/000000039769.jpg"}, {"type": "text", "text": "Please describe the image explicitly."}, ], } ] inputs = processor.apply_chat_template( messages, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt" ).to(torch_device, dtype=torch.float16) with torch.no_grad(): generate_ids = model.generate(**inputs, max_new_tokens=20, do_sample=False) decoded_output = processor.decode( generate_ids[0, inputs["input_ids"].shape[1] :], skip_special_tokens=True ) expected_outputs = Expectations( { ("xpu", 3): 'The image depicts a cozy scene of two cats resting on a bright pink blanket. The cats,', # 4-bit ("cuda", 7): 'The image depicts two cats comfortably resting on a pink blanket spread across a sofa. The cats,', ("cuda", 8): 'The image depicts a cozy scene of two cats resting on a bright pink blanket. The cats,', } ) # fmt: skip expected_output = expected_outputs.get_expectation() self.assertEqual(decoded_output, expected_output) @slow @require_torch_accelerator def test_small_model_integration_batched_generate(self): processor = AutoProcessor.from_pretrained(self.model_checkpoint) model = self.get_model() # Prepare inputs messages = [ [ { "role": "user", "content": [ {"type": "image", "url": "https://llava-vl.github.io/static/images/view.jpg"}, {"type": "text", "text": "Write a haiku for this image"}, ], }, ], [ { "role": "user", "content": [ { "type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg", }, {"type": "text", "text": "Describe this image"}, ], }, ], ] inputs = processor.apply_chat_template( messages, padding=True, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt" ).to(model.device, dtype=torch.float16) output = model.generate(**inputs, do_sample=False, max_new_tokens=25) # Check first output decoded_output = processor.decode(output[0, inputs["input_ids"].shape[1] :], skip_special_tokens=True) expected_outputs = Expectations( { ("xpu", 3): "Wooden bridge stretches\nInto still waters, mountains gleam\nPeaceful forest scene", # 4-bit ("cuda", 7): "Wooden bridge stretches\nMirrored lake below, mountains rise\nPeaceful, serene", ("cuda", 8): 'Wooden path to water,\nMountains echo in stillness,\nPeaceful forest scene.', } ) # fmt: skip expected_output = expected_outputs.get_expectation() self.assertEqual( decoded_output, expected_output, f"Decoded output: {decoded_output}\nExpected output: {expected_output}", ) # Check second output decoded_output = processor.decode(output[1, inputs["input_ids"].shape[1] :], skip_special_tokens=True) expected_outputs = Expectations( { ("xpu", 3): 'This vibrant image captures a bustling street scene in a Chinese-influenced neighborhood. The focal point is a striking red stop sign', # 4-bit ("cuda", 7): 'This vibrant image captures a bustling street scene in a multicultural urban area, featuring a traditional Chinese gate adorned with intricate red and', ("cuda", 8): 'This image captures a vibrant street scene in a bustling urban area, likely in an Asian city. The focal point is a', } ) # fmt: skip expected_output = expected_outputs.get_expectation() self.assertEqual( decoded_output, expected_output, f"Decoded output: {decoded_output}\nExpected output: {expected_output}", ) @slow @require_torch_accelerator @require_deterministic_for_xpu def test_small_model_integration_batched_generate_multi_image(self): processor = AutoProcessor.from_pretrained(self.model_checkpoint) model = self.get_model() # Prepare inputs messages = [ [ { "role": "user", "content": [ {"type": "image", "url": "https://llava-vl.github.io/static/images/view.jpg"}, {"type": "text", "text": "Write a haiku for this image"}, ], }, ], [ { "role": "user", "content": [ { "type": "image", "url": "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg", }, { "type": "image", "url": "https://thumbs.dreamstime.com/b/golden-gate-bridge-san-francisco-purple-flowers-california-echium-candicans-36805947.jpg", }, { "type": "text", "text": "These images depict two different landmarks. Can you identify them?", }, ], }, ], ] inputs = processor.apply_chat_template( messages, padding=True, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt" ).to(model.device, dtype=torch.float16) output = model.generate(**inputs, do_sample=False, max_new_tokens=25) # Check first output decoded_output = processor.decode(output[0, inputs["input_ids"].shape[1] :], skip_special_tokens=True) # Batching seems to alter the output slightly, but it is also the case in the original implementation. This seems to be expected: https://github.com/huggingface/transformers/issues/23017#issuecomment-1649630232 expected_outputs = Expectations( { ("xpu", 3): "Wooden path to water,\nMountains echo in stillness,\nPeaceful forest scene.", ("cuda", 7): 'Wooden bridge stretches\nMirrored lake below, mountains rise\nPeaceful, serene', ("cuda", 8): 'Wooden path to water,\nMountains echo in stillness,\nPeaceful forest scene.', } ) # fmt: skip expected_output = expected_outputs.get_expectation() self.assertEqual( decoded_output, expected_output, f"Decoded output: {decoded_output}\nExpected output: {expected_output}", ) # Check second output decoded_output = processor.decode(output[1, inputs["input_ids"].shape[1] :], skip_special_tokens=True) expected_outputs = Expectations( { ("xpu", 3): "The first image showcases the Statue of Liberty, a colossal neoclassical sculpture on Liberty Island in New York Harbor. Standing at ", ("cuda", 7): 'The first image showcases the Statue of Liberty, a monumental sculpture located on Liberty Island in New York Harbor. Standing atop a', ("cuda", 8): 'The first image showcases the Statue of Liberty, a colossal neoclassical sculpture on Liberty Island in New York Harbor. Standing at ', } ) # fmt: skip expected_output = expected_outputs.get_expectation() self.assertEqual( decoded_output, expected_output, f"Decoded output: {decoded_output}\nExpected output: {expected_output}", )
AyaVisionIntegrationTest
python
pandas-dev__pandas
pandas/tests/indexes/datetimes/test_date_range.py
{ "start": 64465, "end": 66065 }
class ____: def test_date_range_unit_inference_matching_unit(self, unit): start = Timestamp("2025-11-25").as_unit(unit) end = Timestamp("2025-11-26").as_unit(unit) dti = date_range(start, end, freq="D") assert dti.unit == unit def test_date_range_unit_inference_mismatched_unit(self, unit): start = Timestamp("2025-11-25").as_unit(unit) end = Timestamp("2025-11-26").as_unit("s") dti = date_range(start, end, freq="D") assert dti.unit == unit dti = date_range(start, end.as_unit("ns"), freq="D") assert dti.unit == "ns" def test_date_range_unit_inference_tick(self): start = Timestamp("2025-11-25").as_unit("ms") end = Timestamp("2025-11-26").as_unit("s") dti = date_range(start, end, freq="2000000us") assert dti.unit == "us" dti = date_range(start, end.as_unit("ns"), freq="2000000us") assert dti.unit == "ns" def test_date_range_unit_inference_dateoffset_freq(self): start = Timestamp("2025-11-25 09:00:00").as_unit("s") end = Timestamp("2025-11-25 09:00:02").as_unit("s") off = DateOffset(microseconds=2_000_000) dti = date_range(start, end, freq=off) assert dti.unit == "us" off = DateOffset(milliseconds=2) dti = date_range(start, end, freq=off) assert dti.unit == "ms" end2 = start + Timedelta(microseconds=2).as_unit("us") off = DateOffset(nanoseconds=2) dti = date_range(start, end2, freq=off) assert dti.unit == "ns"
TestDateRangeUnitInference
python
sympy__sympy
sympy/physics/quantum/tests/test_commutator.py
{ "start": 2034, "end": 2727 }
class ____(Operator): def _eval_commutator_Foo(self, foo): return Integer(1) def test_eval_commutator(): F = Foo('F') B = Bar('B') T = Tam('T') assert Comm(F, B).doit() == 0 assert Comm(B, F).doit() == 0 assert Comm(F, T).doit() == -1 assert Comm(T, F).doit() == 1 assert Comm(B, T).doit() == B*T - T*B assert Comm(F**2, B).expand(commutator=True).doit() == 0 assert Comm(F**2, T).expand(commutator=True).doit() == -2*F assert Comm(F, T**2).expand(commutator=True).doit() == -2*T assert Comm(T**2, F).expand(commutator=True).doit() == 2*T assert Comm(T**2, F**3).expand(commutator=True).doit() == 2*F*T*F + 2*F**2*T + 2*T*F**2
Tam
python
walkccc__LeetCode
solutions/1150. Check If a Number Is Majority Element in a Sorted Array/1150.py
{ "start": 0, "end": 201 }
class ____: def isMajorityElement(self, nums: list[int], target: int) -> bool: n = len(nums) i = bisect.bisect_left(nums, target) return i + n // 2 < n and nums[i + n // 2] == target
Solution
python
apache__airflow
airflow-core/src/airflow/models/crypto.py
{ "start": 1365, "end": 2128 }
class ____: """ A "Null" encryptor class that doesn't encrypt or decrypt but that presents a similar interface to Fernet. The purpose of this is to make the rest of the code not have to know the difference, and to only display the message once, not 20 times when `airflow db migrate` is run. """ is_encrypted = False def decrypt(self, msg: bytes | str, ttl: int | None = None) -> bytes: """Decrypt with Fernet.""" if isinstance(msg, bytes): return msg if isinstance(msg, str): return msg.encode("utf-8") raise ValueError(f"Expected bytes or str, got {type(msg)}") def encrypt(self, msg: bytes) -> bytes: """Encrypt with Fernet.""" return msg
_NullFernet
python
kamyu104__LeetCode-Solutions
Python/reverse-vowels-of-a-string.py
{ "start": 29, "end": 550 }
class ____(object): def reverseVowels(self, s): """ :type s: str :rtype: str """ vowels = "aeiou" string = list(s) i, j = 0, len(s) - 1 while i < j: if string[i].lower() not in vowels: i += 1 elif string[j].lower() not in vowels: j -= 1 else: string[i], string[j] = string[j], string[i] i += 1 j -= 1 return "".join(string)
Solution
python
tensorflow__tensorflow
tensorflow/python/trackable/data_structures_test.py
{ "start": 1536, "end": 5057 }
class ____(test.TestCase): def testJSONSerialization(self): obj = autotrackable.AutoTrackable() obj.l = [1] json.dumps(obj.l, default=serialization.get_json_type) def testNotTrackable(self): class NotTrackable(object): pass with self.assertRaises(ValueError): data_structures.List([NotTrackable()]) def testCallNotImplemented(self): with self.assertRaisesRegex(TypeError, "not callable"): data_structures.List()(1.) # pylint: disable=not-callable def testNoPop(self): with self.assertRaises(AttributeError): data_structures.List().pop() def testNesting(self): with context.graph_mode(): inner = data_structures.List() outer = data_structures.List([inner]) class TestDense(module.Module): def __init__(self): self.w = variables.Variable(1.0) self.b = variables.Variable(0.0) def __call__(self, inputs): return self.w * inputs + self.b inner.append(TestDense()) inner[0](array_ops.ones([2, 3])) self.assertLen(outer.variables, 2) self.assertIsInstance( outer.variables[0], resource_variable_ops.ResourceVariable) def testNonLayerVariables(self): v = resource_variable_ops.ResourceVariable([1.]) l = data_structures.List([v]) self.assertTrue(l.trainable) self.assertEqual([], l.layers) self.assertEqual([v], l.variables) self.assertEqual([v], l.trainable_weights) self.assertEqual([], l.non_trainable_variables) l.trainable = False self.assertEqual([v], l.variables) self.assertEqual([], l.trainable_variables) self.assertEqual([v], l.non_trainable_variables) l.trainable = True v2 = resource_variable_ops.ResourceVariable(1., trainable=False) l.append(v2) self.assertEqual([v, v2], l.weights) self.assertEqual([v], l.trainable_weights) self.assertEqual([v2], l.non_trainable_weights) def testCopy(self): v1 = resource_variable_ops.ResourceVariable(1.) v2 = resource_variable_ops.ResourceVariable(1.) v3 = resource_variable_ops.ResourceVariable(1.) l1 = data_structures.List([v1, v2]) l2 = l1.copy() l2.append(v3) self.assertEqual(list(l1), [v1, v2]) self.assertEqual(list(l2), [v1, v2, v3]) def testSlicing(self): v1 = resource_variable_ops.ResourceVariable(1.) v2 = resource_variable_ops.ResourceVariable(1.) v3 = resource_variable_ops.ResourceVariable(1.) v4 = resource_variable_ops.ResourceVariable(1.) l = data_structures.List([v1, v2, v3, v4]) self.assertEqual(l[1:], [v2, v3, v4]) self.assertEqual(l[1:-1], [v2, v3]) self.assertEqual(l[:-1], [v1, v2, v3]) def testHash(self): has_sequences = {data_structures.List(), data_structures.List()} self.assertEqual(2, len(has_sequences)) self.assertNotIn(data_structures.List(), has_sequences) def testIMul_zero(self): l = data_structures.List([]) with self.assertRaisesRegex(ValueError, "List only supports append"): l *= 0 def testIMul(self): v = resource_variable_ops.ResourceVariable(1.) l = data_structures.List([v]) l *= 2 self.assertEqual(list(l), [v] * 2) def testMul(self): v = resource_variable_ops.ResourceVariable(1.) l = data_structures.List([v, v, v]) self.assertEqual(list(l * 2), [v, v, v] * 2) def testRMul(self): v = resource_variable_ops.ResourceVariable(1.) l = data_structures.List([v, v, v]) self.assertEqual(list(2 * l), [v, v, v] * 2)
ListTests
python
getsentry__sentry
src/sentry/grouping/enhancer/matchers.py
{ "start": 10861, "end": 10920 }
class ____(PathLikeMatch): field = "package"
PackageMatch
python
huggingface__transformers
src/transformers/models/depth_anything/configuration_depth_anything.py
{ "start": 924, "end": 7505 }
class ____(PreTrainedConfig): r""" This is the configuration class to store the configuration of a [`DepthAnythingModel`]. It is used to instantiate a DepthAnything model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the DepthAnything [LiheYoung/depth-anything-small-hf](https://huggingface.co/LiheYoung/depth-anything-small-hf) architecture. Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PreTrainedConfig`] for more information. Args: backbone_config (`Union[dict[str, Any], PreTrainedConfig]`, *optional*): The configuration of the backbone model. Only used in case `is_hybrid` is `True` or in case you want to leverage the [`AutoBackbone`] API. backbone (`str`, *optional*): Name of backbone to use when `backbone_config` is `None`. If `use_pretrained_backbone` is `True`, this will load the corresponding pretrained weights from the timm or transformers library. If `use_pretrained_backbone` is `False`, this loads the backbone's config and uses that to initialize the backbone with random weights. use_pretrained_backbone (`bool`, *optional*, defaults to `False`): Whether to use pretrained weights for the backbone. use_timm_backbone (`bool`, *optional*, defaults to `False`): Whether or not to use the `timm` library for the backbone. If set to `False`, will use the [`AutoBackbone`] API. backbone_kwargs (`dict`, *optional*): Keyword arguments to be passed to AutoBackbone when loading from a checkpoint e.g. `{'out_indices': (0, 1, 2, 3)}`. Cannot be specified if `backbone_config` is set. patch_size (`int`, *optional*, defaults to 14): The size of the patches to extract from the backbone features. initializer_range (`float`, *optional*, defaults to 0.02): The standard deviation of the truncated_normal_initializer for initializing all weight matrices. reassemble_hidden_size (`int`, *optional*, defaults to 384): The number of input channels of the reassemble layers. reassemble_factors (`list[int]`, *optional*, defaults to `[4, 2, 1, 0.5]`): The up/downsampling factors of the reassemble layers. neck_hidden_sizes (`list[str]`, *optional*, defaults to `[48, 96, 192, 384]`): The hidden sizes to project to for the feature maps of the backbone. fusion_hidden_size (`int`, *optional*, defaults to 64): The number of channels before fusion. head_in_index (`int`, *optional*, defaults to -1): The index of the features to use in the depth estimation head. head_hidden_size (`int`, *optional*, defaults to 32): The number of output channels in the second convolution of the depth estimation head. depth_estimation_type (`str`, *optional*, defaults to `"relative"`): The type of depth estimation to use. Can be one of `["relative", "metric"]`. max_depth (`float`, *optional*): The maximum depth to use for the "metric" depth estimation head. 20 should be used for indoor models and 80 for outdoor models. For "relative" depth estimation, this value is ignored. Example: ```python >>> from transformers import DepthAnythingConfig, DepthAnythingForDepthEstimation >>> # Initializing a DepthAnything small style configuration >>> configuration = DepthAnythingConfig() >>> # Initializing a model from the DepthAnything small style configuration >>> model = DepthAnythingForDepthEstimation(configuration) >>> # Accessing the model configuration >>> configuration = model.config ```""" model_type = "depth_anything" sub_configs = {"backbone_config": AutoConfig} def __init__( self, backbone_config=None, backbone=None, use_pretrained_backbone=False, use_timm_backbone=False, backbone_kwargs=None, patch_size=14, initializer_range=0.02, reassemble_hidden_size=384, reassemble_factors=[4, 2, 1, 0.5], neck_hidden_sizes=[48, 96, 192, 384], fusion_hidden_size=64, head_in_index=-1, head_hidden_size=32, depth_estimation_type="relative", max_depth=None, **kwargs, ): if backbone_config is None and backbone is None: logger.info("`backbone_config` is `None`. Initializing the config with the default `Dinov2` backbone.") backbone_config = CONFIG_MAPPING["dinov2"]( image_size=518, hidden_size=384, num_attention_heads=6, out_indices=[9, 10, 11, 12], apply_layernorm=True, reshape_hidden_states=False, ) elif isinstance(backbone_config, dict): backbone_model_type = backbone_config.get("model_type") config_class = CONFIG_MAPPING[backbone_model_type] backbone_config = config_class.from_dict(backbone_config) verify_backbone_config_arguments( use_timm_backbone=use_timm_backbone, use_pretrained_backbone=use_pretrained_backbone, backbone=backbone, backbone_config=backbone_config, backbone_kwargs=backbone_kwargs, ) self.backbone_config = backbone_config self.backbone = backbone self.use_pretrained_backbone = use_pretrained_backbone self.use_timm_backbone = use_timm_backbone self.backbone_kwargs = backbone_kwargs self.reassemble_hidden_size = reassemble_hidden_size self.patch_size = patch_size self.initializer_range = initializer_range self.reassemble_factors = reassemble_factors self.neck_hidden_sizes = neck_hidden_sizes self.fusion_hidden_size = fusion_hidden_size self.head_in_index = head_in_index self.head_hidden_size = head_hidden_size if depth_estimation_type not in ["relative", "metric"]: raise ValueError("depth_estimation_type must be one of ['relative', 'metric']") self.depth_estimation_type = depth_estimation_type self.max_depth = max_depth if max_depth else 1 super().__init__(**kwargs) __all__ = ["DepthAnythingConfig"]
DepthAnythingConfig
python
huggingface__transformers
src/transformers/models/sam2_video/configuration_sam2_video.py
{ "start": 3388, "end": 6705 }
class ____(PreTrainedConfig): r""" This is the configuration class to store the configuration of a [`Sam2VideoMaskDecoder`]. It is used to instantiate a SAM2_VIDEO memory encoder according to the specified arguments, defining the model architecture. Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PreTrainedConfig`] for more information. Args: hidden_size (`int`, *optional*, defaults to 256): Dimensionality of the hidden states. hidden_act (`str`, *optional*, defaults to `"gelu"`): The non-linear activation function in the SAM2_VIDEO mask decoder. mlp_dim (`int`, *optional*, defaults to 2048): The dimension of the MLP in the two-way transformer. num_hidden_layers (`int`, *optional*, defaults to 2): The number of hidden layers in the two-way transformer. num_attention_heads (`int`, *optional*, defaults to 8): The number of attention heads in the two-way transformer. attention_downsample_rate (`int`, *optional*, defaults to 2): The downsample rate for the attention layers. num_multimask_outputs (`int`, *optional*, defaults to 3): The number of multimask outputs. iou_head_depth (`int`, *optional*, defaults to 3): The depth of the IoU head. iou_head_hidden_dim (`int`, *optional*, defaults to 256): The hidden dimension of the IoU head. dynamic_multimask_via_stability (`bool`, *optional*, defaults to `True`): Whether to use dynamic multimask via stability. dynamic_multimask_stability_delta (`float`, *optional*, defaults to 0.05): The stability delta for the dynamic multimask. dynamic_multimask_stability_thresh (`float`, *optional*, defaults to 0.98): The stability threshold for the dynamic multimask. """ base_config_key = "mask_decoder_config" def __init__( self, hidden_size=256, hidden_act="gelu", mlp_dim=2048, num_hidden_layers=2, num_attention_heads=8, attention_downsample_rate=2, num_multimask_outputs=3, iou_head_depth=3, iou_head_hidden_dim=256, dynamic_multimask_via_stability=True, dynamic_multimask_stability_delta=0.05, dynamic_multimask_stability_thresh=0.98, **kwargs, ): super().__init__(**kwargs) self.hidden_size = hidden_size self.num_multimask_outputs = num_multimask_outputs self.hidden_act = hidden_act self.iou_head_depth = iou_head_depth self.iou_head_hidden_dim = iou_head_hidden_dim self.dynamic_multimask_via_stability = dynamic_multimask_via_stability self.dynamic_multimask_stability_delta = dynamic_multimask_stability_delta self.dynamic_multimask_stability_thresh = dynamic_multimask_stability_thresh # TwoWayTransformer configuration self.num_hidden_layers = num_hidden_layers self.hidden_size = hidden_size self.num_attention_heads = num_attention_heads self.mlp_dim = mlp_dim self.attention_downsample_rate = attention_downsample_rate
Sam2VideoMaskDecoderConfig
python
doocs__leetcode
lcof2/剑指 Offer II 069. 山峰数组的顶部/Solution.py
{ "start": 0, "end": 320 }
class ____: def peakIndexInMountainArray(self, arr: List[int]) -> int: left, right = 1, len(arr) - 2 while left < right: mid = (left + right) >> 1 if arr[mid] > arr[mid + 1]: right = mid else: left = mid + 1 return left
Solution
python
pennersr__django-allauth
allauth/socialaccount/providers/base/constants.py
{ "start": 91, "end": 211 }
class ____: AUTHENTICATE = "authenticate" REAUTHENTICATE = "reauthenticate" REREQUEST = "rerequest"
AuthAction
python
fluentpython__example-code
21-class-metaprog/bulkfood/model_v7.py
{ "start": 1290, "end": 1694 }
class ____(type): """Metaclass for business entities with validated fields""" def __init__(cls, name, bases, attr_dict): super().__init__(name, bases, attr_dict) # <1> for key, attr in attr_dict.items(): # <2> if isinstance(attr, Validated): type_name = type(attr).__name__ attr.storage_name = '_{}#{}'.format(type_name, key)
EntityMeta
python
getsentry__sentry
tests/sentry/monitors/endpoints/test_organization_detector_index.py
{ "start": 3376, "end": 8110 }
class ____(APITestCase): endpoint = "sentry-api-0-organization-detector-index" method = "post" def setUp(self): super().setUp() self.login_as(user=self.user) def _get_detector_post_data(self, **overrides): data = { "projectId": self.project.id, "type": MonitorIncidentType.slug, "name": "Test Monitor Detector", "dataSources": [ { "name": "Test Monitor", "config": { "schedule": "0 * * * *", "scheduleType": "crontab", }, } ], } data.update(overrides) return data def test_create_monitor_incident_detector_validates_correctly(self): data = self._get_detector_post_data() response = self.get_success_response( self.organization.slug, **data, status_code=201, ) assert response.data["name"] == "Test Monitor Detector" assert response.data["type"] == MonitorIncidentType.slug monitor = Monitor.objects.get(organization_id=self.organization.id, slug="test-monitor") assert monitor.name == "Test Monitor" assert monitor.config["schedule"] == "0 * * * *" assert monitor.config["schedule_type"] == ScheduleType.CRONTAB assert monitor.project_id == self.project.id assert monitor.organization_id == self.organization.id detector = Detector.objects.get(id=response.data["id"]) assert detector.name == "Test Monitor Detector" assert detector.type == MonitorIncidentType.slug assert detector.project_id == self.project.id data_source = DataSource.objects.get( organization_id=self.organization.id, type=DATA_SOURCE_CRON_MONITOR, source_id=str(monitor.id), ) assert DataSourceDetector.objects.filter( data_source=data_source, detector=detector ).exists() data_sources = response.data["dataSources"] assert len(data_sources) == 1 data_source_data = data_sources[0] assert data_source_data["type"] == DATA_SOURCE_CRON_MONITOR assert data_source_data["sourceId"] == str(monitor.id) expected_monitor_data = serialize(monitor, user=self.user, serializer=MonitorSerializer()) assert data_source_data["queryObj"] == expected_monitor_data def test_create_monitor_incident_detector_validation_error(self): data = self._get_detector_post_data( dataSources=[ { "config": { "schedule": "invalid cron", "scheduleType": "crontab", }, } ] ) response = self.get_error_response( self.organization.slug, **data, status_code=status.HTTP_400_BAD_REQUEST, ) assert "dataSources" in response.data assert "Either name or slug must be provided" in str(response.data["dataSources"]) def test_create_monitor_with_optional_fields(self): data = self._get_detector_post_data( dataSources=[ { "name": "Full Config Monitor", "slug": "full-config-monitor", "status": "disabled", "isMuted": False, "config": { "schedule": "*/30 * * * *", "scheduleType": "crontab", "checkinMargin": 15, "maxRuntime": 120, "timezone": "America/New_York", "failureIssueThreshold": 3, "recoveryThreshold": 2, }, } ], ) self.get_success_response( self.organization.slug, **data, status_code=201, ) monitor = Monitor.objects.get( organization_id=self.organization.id, slug="full-config-monitor" ) assert monitor.name == "Full Config Monitor" assert monitor.status == ObjectStatus.DISABLED assert is_monitor_muted(monitor) is False assert monitor.config["schedule"] == "*/30 * * * *" assert monitor.config["checkin_margin"] == 15 assert monitor.config["max_runtime"] == 120 assert monitor.config["timezone"] == "America/New_York" assert monitor.config["failure_issue_threshold"] == 3 assert monitor.config["recovery_threshold"] == 2 @region_silo_test
OrganizationDetectorIndexPostTest
python
pytorch__pytorch
torch/_dynamo/replay_record.py
{ "start": 1955, "end": 4389 }
class ____: LOCAL_MOD_PREFIX = "___local_mod_" code: CodeType closure: tuple[CellType] globals: dict[str, Any] = field(default_factory=dict) locals: dict[str, Any] = field(default_factory=dict) builtins: dict[str, Any] = field(default_factory=dict) code_options: dict[str, Any] = field(default_factory=dict) name_to_modrec: dict[str, ModuleRecord] = field(default_factory=dict) def add_local_var(self, name: str, var: Any) -> None: if isinstance(var, ModuleType): self.locals[name] = self._add_mod(var) else: self.locals[name] = var def add_global_var(self, name: str, var: Any) -> None: if isinstance(var, ModuleType): self.globals[name] = self._add_mod(var) else: self.globals[name] = var def add_local_mod(self, name: str, mod: ModuleType) -> None: assert isinstance(mod, ModuleType) self.add_global_var(name, mod) def record_module_access(self, mod: ModuleType, name: str, val: Any) -> None: if isinstance(val, ModuleType): self.name_to_modrec[mod.__name__].accessed_attrs[name] = self._add_mod(val) return if mod.__name__ in self.name_to_modrec: self.name_to_modrec[mod.__name__].accessed_attrs[name] = val def get_record(self) -> ExecutionRecord: return ExecutionRecord( self.code, self.closure, ExecutionRecorder._resolve_modules(self.globals), ExecutionRecorder._resolve_modules(self.locals), self.builtins.copy(), self.code_options.copy(), ) def _add_mod(self, mod: ModuleType) -> ModuleRecord: if mod.__name__ not in self.name_to_modrec: self.name_to_modrec[mod.__name__] = ModuleRecord(mod) return self.name_to_modrec[mod.__name__] @classmethod def _resolve_modules(cls, vars: dict[str, Any]) -> dict[str, Any]: def resolve_module(var: Any) -> Any: if not isinstance(var, ModuleRecord): return var dummy_mod = DummyModule(var.module.__name__) for attr_name, attr_value in var.accessed_attrs.items(): attr_value = resolve_module(attr_value) dummy_mod.__setattr__(attr_name, attr_value) return dummy_mod return {k: resolve_module(v) for k, v in vars.items()}
ExecutionRecorder
python
ray-project__ray
python/ray/autoscaler/command_runner.py
{ "start": 115, "end": 3464 }
class ____: """Interface to run commands on a remote cluster node. **Important**: This is an INTERNAL API that is only exposed for the purpose of implementing custom node providers. It is not allowed to call into CommandRunner methods from any Ray package outside the autoscaler, only to define new implementations for use with the "external" node provider option. Command runner instances are returned by provider.get_command_runner().""" def run( self, cmd: Optional[str] = None, timeout: int = 120, exit_on_fail: bool = False, port_forward: Optional[List[Tuple[int, int]]] = None, with_output: bool = False, environment_variables: Optional[Dict[str, object]] = None, run_env: str = "auto", ssh_options_override_ssh_key: str = "", shutdown_after_run: bool = False, ) -> str: """Run the given command on the cluster node and optionally get output. WARNING: the cloudgateway needs arguments of "run" function to be json dumpable to send them over HTTP requests. Args: cmd: The command to run. timeout: The command timeout in seconds. exit_on_fail: Whether to sys exit on failure. port_forward: List of (local, remote) ports to forward, or a single tuple. with_output: Whether to return output. environment_variables (Dict[str, str | int | Dict[str, str]): Environment variables that `cmd` should be run with. run_env: Options: docker/host/auto. Used in DockerCommandRunner to determine the run environment. ssh_options_override_ssh_key: if provided, overwrites SSHOptions class with SSHOptions(ssh_options_override_ssh_key). shutdown_after_run: if provided, shutdowns down the machine after executing the command with `sudo shutdown -h now`. """ raise NotImplementedError def run_rsync_up( self, source: str, target: str, options: Optional[Dict[str, Any]] = None ) -> None: """Rsync files up to the cluster node. Args: source: The (local) source directory or file. target: The (remote) destination path. """ raise NotImplementedError def run_rsync_down( self, source: str, target: str, options: Optional[Dict[str, Any]] = None ) -> None: """Rsync files down from the cluster node. Args: source: The (remote) source directory or file. target: The (local) destination path. """ raise NotImplementedError def remote_shell_command_str(self) -> str: """Return the command the user can use to open a shell.""" raise NotImplementedError def run_init( self, *, as_head: bool, file_mounts: Dict[str, str], sync_run_yet: bool ) -> Optional[bool]: """Used to run extra initialization commands. Args: as_head: Run as head image or worker. file_mounts: Files to copy to the head and worker nodes. sync_run_yet: Whether sync has been run yet. Returns: optional: Whether initialization is necessary. """ pass
CommandRunnerInterface
python
streamlit__streamlit
lib/streamlit/vendor/pympler/asizeof.py
{ "start": 28216, "end": 29127 }
class ____(object): """Store referred object along with the name of the referent. """ __slots__ = ("name", "ref") def __init__(self, name, ref): self.name = name self.ref = ref # class _Slots(tuple): # '''Wrapper class for __slots__ attribute at class definition. # The instance-specific __slots__ attributes are stored in # a "tuple-like" space inside the instance, see Luciano # Ramalho, "Fluent Python", page 274+, O'Reilly, 2016 or # at <http://Books.Google.com/books>, then search for # "Fluent Python" "Space Savings with the __slots__". # ''' # pass # all kinds of _Typedefs i = sys.intern # Python 3+ t = (_kind_static, _kind_dynamic, _kind_derived, _kind_ignored, _kind_inferred) = ( i("static"), i("dynamic"), i("derived"), i("ignored"), i("inferred"), ) _all_kinds = set(t) del i, t
_NamedRef
python
dagster-io__dagster
.buildkite/buildkite-shared/buildkite_shared/step_builders/command_step_builder.py
{ "start": 2181, "end": 20320 }
class ____: _step: CommandStepConfiguration def __init__( self, label, key: Optional[str] = None, timeout_in_minutes: int = DEFAULT_TIMEOUT_IN_MIN, retry_automatically: bool = True, plugins: Optional[list[dict[str, object]]] = None, ): self._secrets = {} self._kubernetes_secrets = [] self._docker_settings = None retry: dict[str, Any] = { "manual": {"permit_on_passed": True}, } if retry_automatically: # This list contains exit codes that should map only to ephemeral infrastructure issues. # Normal test failures (exit code 1), make command failures (exit code 2) and the like # should not be included here. retry["automatic"] = [ # https://buildkite.com/docs/agent/v3#exit-codes {"exit_status": -1, "limit": 2}, # agent lost { "exit_status": -10, "limit": 2, }, # example: https://buildkite.com/dagster/internal/builds/108316#0196fd13-d816-42e7-bf26-b264385b245d {"exit_status": 125, "limit": 2}, # docker daemon error {"exit_status": 128, "limit": 2}, # k8s git clone error {"exit_status": 143, "limit": 2}, # agent lost {"exit_status": 255, "limit": 2}, # agent forced shut down { "exit_status": ECR_LOGIN_FAILURE_EXIT_CODE, "limit": 2, }, # ecr login failed { "exit_status": 28, "limit": 2, }, # node ran out of space, try to reschedule ] self._step = { "agents": {"queue": BuildkiteQueue.MEDIUM.value}, "label": label, "timeout_in_minutes": timeout_in_minutes, "retry": retry, "plugins": plugins or [], } self._requires_docker = True # used for k8s queue if key is not None: self._step["key"] = key self._resources = None def run(self, *argc): self._step["commands"] = list(argc) return self def resources(self, resources: Optional[ResourceRequests]) -> "CommandStepBuilder": self._resources = resources return self def no_docker(self) -> "CommandStepBuilder": self._requires_docker = False return self def on_python_image( self, image, env=None, account_id=AWS_ACCOUNT_ID, region=AWS_ECR_REGION, ): settings = self._base_docker_settings(env) settings["image"] = f"{account_id}.dkr.ecr.{region}.amazonaws.com/{image}" settings["network"] = "kind" self._docker_settings = settings return self def on_specific_image(self, image, extra_docker_plugin_args={}): settings = {"image": image, **extra_docker_plugin_args} if self._docker_settings: self._docker_settings.update(settings) else: self._docker_settings = settings return self def on_integration_slim_image(self, env=None): return self.on_python_image( image="buildkite-test-image-py-slim:prod-1749737887", env=env, ) def on_integration_image( self, ver=SUPPORTED_PYTHON_VERSION, env=None, image_name=BASE_IMAGE_NAME, image_version=BASE_IMAGE_TAG, ecr_account_ids=[AWS_ACCOUNT_ID], ): return self.on_python_image( image=f"{image_name}:py{ver}-{image_version}", env=env, ).with_ecr_login(ecr_account_ids) def with_ecr_login(self, ecr_account_ids=[AWS_ACCOUNT_ID]): assert "plugins" in self._step self._step["plugins"].append( { ECR_PLUGIN: { "login": True, "no-include-email": True, "account_ids": ecr_account_ids, "region": "us-west-2", } } ) return self def with_ecr_passthru(self) -> "CommandStepBuilder": assert self._docker_settings assert self._docker_settings["environment"] assert self._docker_settings["volumes"] self._docker_settings["environment"] = [ *self._docker_settings["environment"], "BUILDKITE_DOCKER_CONFIG_TEMP_DIRECTORY", "DOCKER_CONFIG=/tmp/.docker", ] self._docker_settings["volumes"] = list( set( [ *[v for v in self._docker_settings["volumes"]], # share auth with the docker buildkite-test "$$BUILDKITE_DOCKER_CONFIG_TEMP_DIRECTORY/config.json:/tmp/.docker/config.json", ] ) ) return self def with_artifact_paths(self, *paths): if "artifact_paths" not in self._step: self._step["artifact_paths"] = [] self._step["artifact_paths"].extend(paths) return self def with_condition(self, condition): self._step["if"] = condition return self def with_secret(self, name, reference): self._secrets[name] = reference return self def with_timeout(self, num_minutes): self._step["timeout_in_minutes"] = num_minutes return self def with_retry(self, num_retries): # Update default retry config to blanket limit with num_retries if num_retries is not None and num_retries > 0: self._step["retry"]["automatic"] = {"limit": num_retries} return self def on_queue(self, queue: BuildkiteQueue): self._step["agents"]["queue"] = queue.value return self def with_kubernetes_secret(self, secret: str) -> "CommandStepBuilder": self._kubernetes_secrets.append(secret) return self def concurrency(self, limit): self._step["concurrency"] = limit return self def concurrency_group(self, concurrency_group_name): self._step["concurrency_group"] = concurrency_group_name return self def depends_on(self, dependencies): self._step["depends_on"] = dependencies return self def allow_dependency_failure(self): self._step["allow_dependency_failure"] = True return self def soft_fail(self, fail: bool = True): self._step["soft_fail"] = fail return self def skip_if(self, skip_reason: Optional[str] = None): self._step["skip"] = skip_reason return self def _get_resources(self): cpu = ( self._resources.cpu if self._resources else ("1500m" if self._requires_docker else "500m") ) memory = self._resources.memory if self._resources else None return { "requests": { "cpu": cpu, "memory": memory, "ephemeral-storage": ("10Gi" if self._requires_docker else "5Gi"), }, } def _base_docker_settings(self, env=None): return { "shell": ["/bin/bash", "-xeuc"], "mount-ssh-agent": True, "propagate-environment": False, "expand-volume-vars": True, "volumes": ["/var/run/docker.sock:/var/run/docker.sock", "/tmp:/tmp"], "environment": [ "PYTEST_ADDOPTS", "PYTEST_PLUGINS", "BUILDKITE", "BUILDKITE_BUILD_CHECKOUT_PATH", "BUILDKITE_BUILD_URL", "BUILDKITE_ORGANIZATION_SLUG", "BUILDKITE_PIPELINE_SLUG", "BUILDKITE_ANALYTICS_TOKEN", "BUILDKITE_TEST_QUARANTINE_TOKEN", "BUILDKITE_TEST_SUITE_SLUG", # Buildkite uses this to tag tests in Test Engine "BUILDKITE_BRANCH", "BUILDKITE_COMMIT", "BUILDKITE_MESSAGE", ] + [ # these are exposed via the ECR plugin and then threaded through # to kubernetes. see https://github.com/buildkite-plugins/ecr-buildkite-plugin "AWS_SECRET_ACCESS_KEY", "AWS_ACCESS_KEY_ID", "AWS_SESSION_TOKEN", "AWS_REGION", "AWS_ACCOUNT_ID", "UV_DEFAULT_INDEX", ] + [ # needed by our own stuff "DAGSTER_INTERNAL_GIT_REPO_DIR", "DAGSTER_GIT_REPO_DIR", "COMBINED_COMMIT_HASH", "DAGSTER_COMMIT_HASH", "INTERNAL_COMMIT_HASH", "DAGSTER_BRANCH", ] + [ # tox related env variables. ideally these are in # the test specification themselves, but for now this is easier "DD_DOGSTATSD_DISABLE", "AWS_DEFAULT_REGION", "TOYS_SNOWFLAKE_ACCOUNT", "TOYS_SNOWFLAKE_PASSWORD", "TOYS_BIGQUERY_PROJECT", "TOYS_BIGQUERY_CREDENTIALS", "TOYS_GCP_PRIVATE_KEY_ID", "TOYS_GCP_PRIVATE_KEY", "TOYS_GCP_CLIENT_EMAIL", "TOYS_GCP_CLIENT_ID", "TOYS_GCP_CLIENT_CERT_URL", "SNOWFLAKE_ACCOUNT", "SNOWFLAKE_USER", "SNOWFLAKE_PASSWORD", "DAGSTER_SERVERLESS_AWS_ACCOUNT_ID", "DAGSTER_SERVERLESS_SERVICE_NAME", "DAGSTER_SERVERLESS_AWS_ACCOUNT_NAME", "DAGSTER_SERVERLESS_SUBNETS_PER_VPC", ] + [ "DATADOG_API_KEY", "FOSSA_API_KEY", ] + ["PYTEST_DEBUG_TEMPROOT=/tmp"] + (env or []), "mount-buildkite-agent": True, } def _base_k8s_settings(self) -> Mapping[Any, Any]: buildkite_shell = "/bin/bash -e -c" assert self._docker_settings if self._docker_settings["image"] == "hashicorp/terraform:light": buildkite_shell = "/bin/sh -e -c" sidecars = [] volumes = [] volume_mounts = [] if self._requires_docker: sidecars.append( { "image": "public.ecr.aws/docker/library/docker:20.10.16-dind", "command": ["dockerd-entrypoint.sh"], "resources": { "requests": { "cpu": self._resources.docker_cpu if self._resources else "500m" } }, "env": [ { "name": "DOCKER_TLS_CERTDIR", "value": "", }, ], "volumeMounts": [ { "mountPath": "/var/run", "name": "docker-sock", } ], "securityContext": { "privileged": True, "allowPrivilegeEscalation": True, }, } ) volumes.append( { "name": "docker-sock", "emptyDir": {}, } ) volume_mounts.append( { "mountPath": "/var/run/", "name": "docker-sock", }, ) return { "gitEnvFrom": [{"secretRef": {"name": "git-ssh-credentials"}}], "mirrorVolumeMounts": True, "sidecars": sidecars, "podSpec": { "serviceAccountName": "buildkite-job", "containers": [ { "image": self._docker_settings["image"], "env": [ { "name": "BUILDKITE_SHELL", "value": buildkite_shell, }, # { # "name": "UV_DEFAULT_INDEX", # "value": "http://devpi.buildkite-agent.svc.cluster.local/root/pypi", # }, { "name": "POD_NAME", "valueFrom": {"fieldRef": {"fieldPath": "metadata.name"}}, }, { "name": "NODE_NAME", "valueFrom": {"fieldRef": {"fieldPath": "spec.nodeName"}}, }, { "name": "INTERNAL_BUILDKITE_TEST_ANALYTICS_TOKEN", "valueFrom": { "secretKeyRef": { "name": "buildkite-dagster-secrets", "key": "INTERNAL_BUILDKITE_TEST_ANALYTICS_TOKEN", } }, }, { "name": "INTERNAL_BUILDKITE_STEP_ANALYTICS_TOKEN", "valueFrom": { "secretKeyRef": { "name": "buildkite-dagster-secrets", "key": "INTERNAL_BUILDKITE_STEP_ANALYTICS_TOKEN", } }, }, { "name": "DOGFOOD_BUILDKITE_STEP_ANALYTICS_TOKEN", "valueFrom": { "secretKeyRef": { "name": "buildkite-dagster-secrets", "key": "DOGFOOD_BUILDKITE_STEP_ANALYTICS_TOKEN", } }, }, ], "envFrom": [ {"secretRef": {"name": "buildkite-dagster-secrets"}}, {"secretRef": {"name": "honeycomb-api-key"}}, *( [{"secretRef": {"name": "aws-creds"}}] if self._step.get("agents", {}).get("queue") == BuildkiteQueue.KUBERNETES_GKE.value else [] ), *[ {"secretRef": {"name": secret_name}} for secret_name in self._kubernetes_secrets ], ], "resources": self._get_resources(), "volumeMounts": volume_mounts, "securityContext": {"capabilities": {"add": ["SYS_PTRACE"]}}, }, ], "volumes": volumes, }, } def build(self): assert "agents" in self._step on_k8s = self._step["agents"]["queue"] in ( BuildkiteQueue.KUBERNETES_GKE.value, BuildkiteQueue.KUBERNETES_EKS.value, ) if self._requires_docker is False and not on_k8s: raise Exception("you specified .no_docker() but you're not running on kubernetes") if not on_k8s and self._kubernetes_secrets: raise Exception( "Specified a kubernetes secret on a non-kubernetes queue. Please call .on_queue(BuildkiteQueue.KUBERNETES_GKE) or .on_queue(BuildkiteQueue.KUBERNETES_EKS) if you want to run on k8s" ) if on_k8s: # for k8s we take the image that we were going to run in docker # and instead launch it as a pod directly on k8s. to do this # we need to patch the image that buildkite will actually run # during the test step to match. `buildkite-agent bootstrap` (which # is the entrypoint that ends up getting run (via some volume mounting # magic) depends on a BUILDKITE_SHELL variable to actually execute # the specified command (like "terraform fmt -check -recursive"). some # images require /bin/bash, others don't have it, so there's some setting # munging done below as well. if self._docker_settings: self._step["plugins"] = [{"kubernetes": self._base_k8s_settings()}] return self._step # adding SM and DOCKER plugin in build allows secrets to be passed to docker envs assert "plugins" in self._step self._step["plugins"].append({SM_PLUGIN: {"region": "us-west-1", "env": self._secrets}}) if self._docker_settings: for secret in self._secrets.keys(): self._docker_settings["environment"].append(secret) # we need to dedup the env vars to make sure that the ones we set # aren't overridden by the ones that are already set in the parent env # the last one wins envvar_map = {} for ev in self._docker_settings.get("environment", []): k, v = ev.split("=") if "=" in ev else (ev, None) envvar_map[k] = v self._docker_settings["environment"] = [ f"{k}={v}" if v is not None else k for k, v in envvar_map.items() ] assert "plugins" in self._step self._step["plugins"].append({DOCKER_PLUGIN: self._docker_settings}) return self._step StepBuilderMutator = Callable[[CommandStepBuilder], CommandStepBuilder]
CommandStepBuilder
python
pytorch__pytorch
tools/experimental/torchfuzz/operators/nn_functional.py
{ "start": 3735, "end": 7431 }
class ____(Operator): """Operator for torch.nn.functional.linear.""" def __init__(self): super().__init__("torch.nn.functional.linear") @property def torch_op_name(self) -> str | None: """Return the torch operation name.""" return "torch.nn.functional.linear" def can_produce(self, output_spec: Spec) -> bool: """Linear can produce tensor outputs with floating point dtypes.""" if not isinstance(output_spec, TensorSpec): return False # Linear needs at least 1 dimension (output features) if len(output_spec.size) == 0: return False return is_float_dtype(output_spec.dtype) def fuzz_inputs_specs(self, output_spec: Spec) -> list[Spec]: """Generate input specs for linear operation. Linear transformation: y = xW^T + b - input: (..., in_features) - weight: (out_features, in_features) - bias: (out_features,) [optional] - output: (..., out_features) """ if not isinstance(output_spec, TensorSpec): raise ValueError("LinearOperator can only produce TensorSpec outputs") if len(output_spec.size) == 0: raise ValueError("Linear output must have at least 1 dimension") out_features = output_spec.size[-1] batch_shape = output_spec.size[:-1] # Generate reasonable input features size in_features = random.randint(8, 256) # Input tensor: (..., in_features) input_shape = batch_shape + (in_features,) input_spec = TensorSpec( size=input_shape, stride=self._calculate_stride(input_shape), dtype=output_spec.dtype, ) # Weight tensor: (out_features, in_features) weight_spec = TensorSpec( size=(out_features, in_features), stride=(in_features, 1), dtype=output_spec.dtype, ) # Bias tensor: (out_features,) - make bias optional with 50% probability if random.random() < 0.5: bias_spec = TensorSpec( size=(out_features,), stride=(1,), dtype=output_spec.dtype ) return [input_spec, weight_spec, bias_spec] else: return [input_spec, weight_spec] def _calculate_stride(self, size): """Calculate stride for a given size.""" if not size: return () stride = [] current_stride = 1 for dim_size in reversed(size): stride.append(current_stride) current_stride *= dim_size return tuple(reversed(stride)) def codegen( self, output_name: str, input_names: list[str], output_spec: Spec ) -> str: """Generate code for linear operation.""" if not isinstance(output_spec, TensorSpec): raise ValueError("LinearOperator can only produce TensorSpec outputs") # Ensure dtype compatibility by converting all inputs to the expected output dtype target_dtype = str(output_spec.dtype) if len(input_names) == 2: input_name, weight_name = input_names return f"{output_name} = torch.nn.functional.linear({input_name}.to({target_dtype}), {weight_name}.to({target_dtype}))" elif len(input_names) == 3: input_name, weight_name, bias_name = input_names return f"{output_name} = torch.nn.functional.linear({input_name}.to({target_dtype}), {weight_name}.to({target_dtype}), {bias_name}.to({target_dtype}))" else: raise ValueError( "Linear requires 2 or 3 inputs: input, weight, and optional bias" )
LinearOperator