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
getsentry__sentry
src/sentry/models/dashboard_widget.py
{ "start": 1173, "end": 2324 }
class ____(TypesClass): DISCOVER = 0 """ Old way of accessing error events and transaction events simultaneously @deprecated. Use ERROR_EVENTS or TRANSACTION_LIKE instead. """ ISSUE = 1 RELEASE_HEALTH = 2 METRICS = 3 ERROR_EVENTS = 100 """ Error side of the split from Discover. """ TRANSACTION_LIKE = 101 """ This targets transaction-like data from the split from discover. Itt may either use 'Transactions' events or 'PerformanceMetrics' depending on on-demand, MEP metrics, etc. """ SPANS = 102 """ These represent the logs trace item type on the EAP dataset. """ LOGS = 103 """ These represent the tracemetrics item type on the EAP dataset. """ TRACEMETRICS = 104 TYPES = [ (DISCOVER, "discover"), (ISSUE, "issue"), ( RELEASE_HEALTH, "metrics", ), (ERROR_EVENTS, "error-events"), (TRANSACTION_LIKE, "transaction-like"), (SPANS, "spans"), (LOGS, "logs"), (TRACEMETRICS, "tracemetrics"), ] TYPE_NAMES = [t[1] for t in TYPES]
DashboardWidgetTypes
python
getsentry__sentry
src/sentry/utils/arroyo_producer.py
{ "start": 599, "end": 3432 }
class ____: """ A Kafka producer that can be instantiated as a global variable/singleton/service. It is supposed to be used in tasks, where we want to flush the producer on process shutdown. """ def __init__( self, kafka_producer_factory: Callable[[], KafkaProducer], max_futures: int = 1000 ) -> None: self._producer: KafkaProducer | None = None self._factory = kafka_producer_factory self._futures: Deque[_ProducerFuture] = deque() self.max_futures = max_futures def produce( self, destination: ArroyoTopic | Partition, payload: KafkaPayload ) -> _ProducerFuture: future = self._get().produce(destination, payload) self._track_futures(future) return future def _get(self) -> KafkaProducer: if self._producer is None: self._producer = self._factory() atexit.register(self._shutdown) return self._producer def _track_futures(self, future: _ProducerFuture) -> None: self._futures.append(future) if len(self._futures) >= self.max_futures: try: future = self._futures.popleft() except IndexError: return else: future.result() def _shutdown(self) -> None: for future in self._futures: try: future.result() except Exception: pass if self._producer: self._producer.close() def get_arroyo_producer( name: str, topic: Topic, additional_config: dict | None = None, exclude_config_keys: list[str] | None = None, **kafka_producer_kwargs, ) -> KafkaProducer: """ Get an arroyo producer for a given topic. Args: name: Unique identifier for this producer (used as client.id, for metrics and killswitches) topic: The Kafka topic this producer will write to additional_config: Additional Kafka configuration to merge with defaults exclude_config_keys: List of config keys to exclude from the default configuration **kafka_producer_kwargs: Additional keyword arguments passed to KafkaProducer Returns: KafkaProducer """ topic_definition = get_topic_definition(topic) producer_config = get_kafka_producer_cluster_options(topic_definition["cluster"]) # Remove any excluded config keys if exclude_config_keys: for key in exclude_config_keys: producer_config.pop(key, None) # Apply additional config if additional_config: producer_config.update(additional_config) producer_config["client.id"] = name return KafkaProducer( build_kafka_producer_configuration(default_config=producer_config), **kafka_producer_kwargs )
SingletonProducer
python
FactoryBoy__factory_boy
tests/test_regression.py
{ "start": 467, "end": 1700 }
class ____(unittest.TestCase): def test_locale_issue(self): """Regression test for `KeyError: 'locale'` See #785 #786 #787 #788 #790 #796. """ class AuthorFactory(factory.Factory): class Meta: model = Author class Params: unknown = factory.Trait( fullname="", ) fullname = factory.Faker("name") public_author = AuthorFactory(unknown=False) self.assertIsNone(public_author.pseudonym) unknown_author = AuthorFactory(unknown=True) self.assertEqual("", unknown_author.fullname) def test_evaluated_without_locale(self): """Regression test for `KeyError: 'locale'` raised in `evaluate`. See #965 """ class AuthorFactory(factory.Factory): fullname = factory.Faker("name") pseudonym = factory.Maybe( decider=factory.Faker("pybool"), yes_declaration="yes", no_declaration="no", ) class Meta: model = Author author = AuthorFactory() self.assertIn(author.pseudonym, ["yes", "no"])
FakerRegressionTests
python
walkccc__LeetCode
solutions/1447. Simplified Fractions/1447.py
{ "start": 0, "end": 296 }
class ____: def simplifiedFractions(self, n: int) -> list[str]: ans = [] for denominator in range(2, n + 1): for numerator in range(1, denominator): if math.gcd(denominator, numerator) == 1: ans.append(str(numerator) + '/' + str(denominator)) return ans
Solution
python
ray-project__ray
python/ray/train/v2/_internal/callbacks/state_manager.py
{ "start": 1027, "end": 6382 }
class ____(ControllerCallback, WorkerGroupCallback): def after_controller_start(self, train_run_context: TrainRunContext): self._state_manager = TrainStateManager() self._run_name = train_run_context.get_run_config().name self._run_id = train_run_context.run_id # TODO: Should this be generated by the caller? # NOTE: These must be called on the Controller. # The Callback is first initialized on the Driver. core_context = ray.runtime_context.get_runtime_context() self._job_id = core_context.get_job_id() self._controller_actor_id = core_context.get_actor_id() controller_log_file_path = get_train_application_controller_log_path() self._state_manager.create_train_run( id=self._run_id, name=self._run_name, job_id=self._job_id, controller_actor_id=self._controller_actor_id, controller_log_file_path=controller_log_file_path, ) def after_controller_state_update( self, previous_state: TrainControllerState, current_state: TrainControllerState, ): if previous_state._state_type == current_state._state_type: return logger.info( f"[State Transition] {previous_state._state_type.state_name} -> " f"{current_state._state_type.state_name}." ) if isinstance(current_state, SchedulingState): # TODO: This should probably always be ResizeDecision. if isinstance(current_state.scaling_decision, ResizeDecision): resize_decision = current_state.scaling_decision else: resize_decision = None self._state_manager.update_train_run_scheduling( run_id=self._run_id, resize_decision=resize_decision, ) elif isinstance(current_state, RunningState): self._state_manager.update_train_run_running( run_id=self._run_id, ) elif isinstance(current_state, RestartingState): self._state_manager.update_train_run_restarting( run_id=self._run_id, ) elif isinstance(current_state, ResizingState): self._state_manager.update_train_run_resizing( run_id=self._run_id, ) elif isinstance(current_state, ErroredState): self._state_manager.update_train_run_errored( run_id=self._run_id, status_detail=str(current_state.training_failed_error), ) elif isinstance(current_state, FinishedState): self._state_manager.update_train_run_finished( run_id=self._run_id, ) elif isinstance(current_state, AbortedState): self._state_manager.update_train_run_aborted( run_id=self._run_id, ) elif isinstance(current_state, ReschedulingState): # substate of SchedulingState pass elif isinstance(current_state, ShuttingDownState): # substate of RunningState pass def before_worker_group_start(self, worker_group_context: WorkerGroupContext): self._state_manager.create_train_run_attempt( run_id=self._run_id, attempt_id=worker_group_context.run_attempt_id, num_workers=worker_group_context.num_workers, resources_per_worker=worker_group_context.resources_per_worker, ) def after_worker_group_start(self, worker_group: WorkerGroup): worker_group_context: WorkerGroupContext = ( worker_group.get_worker_group_context() ) worker_group_state: WorkerGroupState = worker_group.get_worker_group_state() self._state_manager.update_train_run_attempt_running( run_id=self._run_id, attempt_id=worker_group_context.run_attempt_id, workers=worker_group_state.workers, ) def before_worker_group_shutdown(self, worker_group: WorkerGroup): worker_group_context: WorkerGroupContext = ( worker_group.get_worker_group_context() ) # TODO: Consider passing error reason directly to the callback. # Something along the lines of: # WorkerGroup.shutdown(reason) # -> WorkerGroupCallback.before_worker_group_shutdown(reason) worker_group_poll_status: Optional[ WorkerGroupPollStatus ] = worker_group.get_latest_poll_status() if worker_group_poll_status and worker_group_poll_status.errors: self._state_manager.update_train_run_attempt_errored( run_id=self._run_id, attempt_id=worker_group_context.run_attempt_id, status_detail=worker_group_poll_status.get_error_string(), ) else: self._state_manager.update_train_run_attempt_finished( run_id=self._run_id, attempt_id=worker_group_context.run_attempt_id, ) def before_worker_group_abort(self, worker_group_context: WorkerGroupContext): self._state_manager.update_train_run_attempt_aborted( self._run_id, worker_group_context.run_attempt_id, )
StateManagerCallback
python
sphinx-doc__sphinx
sphinx/domains/cpp/_ast.py
{ "start": 6395, "end": 12874 }
class ____(ASTBase): def __init__( self, names: list[ASTNestedNameElement], templates: list[bool], rooted: bool ) -> None: assert len(names) > 0 self.names = names self.templates = templates assert len(self.names) == len(self.templates) self.rooted = rooted def __eq__(self, other: object) -> bool: if not isinstance(other, ASTNestedName): return NotImplemented return ( self.names == other.names and self.templates == other.templates and self.rooted == other.rooted ) def __hash__(self) -> int: return hash((self.names, self.templates, self.rooted)) @property def name(self) -> ASTNestedName: return self def num_templates(self) -> int: count = 0 for n in self.names: if n.is_operator(): continue if n.templateArgs: count += 1 return count def get_id(self, version: int, modifiers: str = '') -> str: if version == 1: tt = str(self) if tt in _id_shorthands_v1: return _id_shorthands_v1[tt] else: return '::'.join(n.get_id(version) for n in self.names) res = [] if len(self.names) > 1 or len(modifiers) > 0: res.append('N') res.append(modifiers) res.extend(n.get_id(version) for n in self.names) if len(self.names) > 1 or len(modifiers) > 0: res.append('E') return ''.join(res) def _stringify(self, transform: StringifyTransform) -> str: res = [] if self.rooted: res.append('') for i in range(len(self.names)): n = self.names[i] if self.templates[i]: res.append('template ' + transform(n)) else: res.append(transform(n)) return '::'.join(res) def describe_signature( self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol ) -> None: verify_description_mode(mode) # just print the name part, with template args, not template params if mode == 'noneIsName': if self.rooted: unreachable = 'Can this happen?' raise AssertionError(unreachable) # TODO: Can this happen? signode += nodes.Text('::') for i in range(len(self.names)): if i != 0: unreachable = 'Can this happen?' raise AssertionError(unreachable) # TODO: Can this happen? signode += nodes.Text('::blah') n = self.names[i] if self.templates[i]: unreachable = 'Can this happen?' raise AssertionError(unreachable) # TODO: Can this happen? signode += nodes.Text('template') signode += nodes.Text(' ') n.describe_signature(signode, mode, env, '', symbol) elif mode == 'param': assert not self.rooted, str(self) assert len(self.names) == 1 assert not self.templates[0] self.names[0].describe_signature(signode, 'param', env, '', symbol) elif mode in {'markType', 'lastIsName', 'markName'}: # Each element should be a pending xref targeting the complete # prefix. however, only the identifier part should be a link, such # that template args can be a link as well. # For 'lastIsName' we should also prepend template parameter lists. template_params: list[Any] = [] if mode == 'lastIsName': assert symbol is not None if symbol.declaration.templatePrefix is not None: template_params = symbol.declaration.templatePrefix.templates i_template_params = 0 template_params_prefix = '' prefix = '' first = True names = self.names[:-1] if mode == 'lastIsName' else self.names # If lastIsName, then wrap all of the prefix in a desc_addname, # else append directly to signode. # NOTE: Breathe previously relied on the prefix being in the desc_addname node, # so it can remove it in inner declarations. dest = signode if mode == 'lastIsName': dest = addnodes.desc_addname() if self.rooted: prefix += '::' if mode == 'lastIsName' and len(names) == 0: signode += addnodes.desc_sig_punctuation('::', '::') else: dest += addnodes.desc_sig_punctuation('::', '::') for i in range(len(names)): nne = names[i] template = self.templates[i] if not first: dest += addnodes.desc_sig_punctuation('::', '::') prefix += '::' if template: dest += addnodes.desc_sig_keyword('template', 'template') dest += addnodes.desc_sig_space() first = False txt_nne = str(nne) if txt_nne: if nne.templateArgs and i_template_params < len(template_params): template_params_prefix += str( template_params[i_template_params] ) i_template_params += 1 nne.describe_signature( dest, 'markType', env, template_params_prefix + prefix, symbol ) prefix += txt_nne if mode == 'lastIsName': if len(self.names) > 1: dest += addnodes.desc_sig_punctuation('::', '::') signode += dest if self.templates[-1]: signode += addnodes.desc_sig_keyword('template', 'template') signode += addnodes.desc_sig_space() self.names[-1].describe_signature(signode, mode, env, '', symbol) else: raise Exception('Unknown description mode: %s' % mode) ################################################################################ # Expressions ################################################################################
ASTNestedName
python
sqlalchemy__sqlalchemy
test/base/test_utils.py
{ "start": 60632, "end": 61899 }
class ____(fixtures.TestBase): baseline = {("a", 1), ("b", 2), ("c", 3)} def _ok(self, instance): iterator = util.dictlike_iteritems(instance) eq_(set(iterator), self.baseline) def _notok(self, instance): assert_raises(TypeError, util.dictlike_iteritems, instance) def test_dict(self): d = dict(a=1, b=2, c=3) self._ok(d) def test_subdict(self): class subdict(dict): pass d = subdict(a=1, b=2, c=3) self._ok(d) def test_object(self): self._notok(object()) def test_duck_2(self): class duck2: def items(duck): return list(self.baseline) self._ok(duck2()) def test_duck_4(self): class duck4: def iterkeys(duck): return iter(["a", "b", "c"]) self._notok(duck4()) def test_duck_5(self): class duck5: def keys(duck): return ["a", "b", "c"] def get(duck, key): return dict(a=1, b=2, c=3).get(key) self._ok(duck5()) def test_duck_6(self): class duck6: def keys(duck): return ["a", "b", "c"] self._notok(duck6())
DictlikeIteritemsTest
python
mwaskom__seaborn
seaborn/_core/moves.py
{ "start": 640, "end": 2143 }
class ____(Move): """ Random displacement along one or both axes to reduce overplotting. Parameters ---------- width : float Magnitude of jitter, relative to mark width, along the orientation axis. If not provided, the default value will be 0 when `x` or `y` are set, otherwise there will be a small amount of jitter applied by default. x : float Magnitude of jitter, in data units, along the x axis. y : float Magnitude of jitter, in data units, along the y axis. Examples -------- .. include:: ../docstrings/objects.Jitter.rst """ width: float | Default = default x: float = 0 y: float = 0 seed: int | None = None def __call__( self, data: DataFrame, groupby: GroupBy, orient: str, scales: dict[str, Scale], ) -> DataFrame: data = data.copy() rng = np.random.default_rng(self.seed) def jitter(data, col, scale): noise = rng.uniform(-.5, +.5, len(data)) offsets = noise * scale return data[col] + offsets if self.width is default: width = 0.0 if self.x or self.y else 0.2 else: width = cast(float, self.width) if self.width: data[orient] = jitter(data, orient, width * data["width"]) if self.x: data["x"] = jitter(data, "x", self.x) if self.y: data["y"] = jitter(data, "y", self.y) return data @dataclass
Jitter
python
run-llama__llama_index
llama-index-integrations/embeddings/llama-index-embeddings-huggingface-api/tests/test_hf_inference.py
{ "start": 557, "end": 4763 }
class ____: def test_class_name( self, hf_inference_api_embedding: HuggingFaceInferenceAPIEmbedding ) -> None: assert ( HuggingFaceInferenceAPIEmbedding.class_name() == HuggingFaceInferenceAPIEmbedding.__name__ ) assert ( hf_inference_api_embedding.class_name() == HuggingFaceInferenceAPIEmbedding.__name__ ) # def test_using_recommended_model(self) -> None: # mock_hub = MagicMock() # mock_hub.InferenceClient.get_recommended_model.return_value = ( # "facebook/bart-base" # ) # with patch.dict("sys.modules", huggingface_hub=mock_hub): # embedding = HuggingFaceInferenceAPIEmbedding(task="feature-extraction") # assert embedding.model_name == "facebook/bart-base" # # mock_hub.InferenceClient.get_recommended_model.assert_called_once_with( # # task="feature-extraction" # # ) def test_embed_query( self, hf_inference_api_embedding: HuggingFaceInferenceAPIEmbedding ) -> None: raw_single_embedding = np.random.default_rng().random( (1, 3, 1024), dtype=np.float32 ) hf_inference_api_embedding.pooling = Pooling.CLS with patch.object( hf_inference_api_embedding._async_client, "feature_extraction", AsyncMock(return_value=raw_single_embedding), ) as mock_feature_extraction: embedding = hf_inference_api_embedding.get_query_embedding("test") assert isinstance(embedding, list) assert len(embedding) == 1024 assert isinstance(embedding[0], float) assert np.all( np.array(embedding, dtype=raw_single_embedding.dtype) == raw_single_embedding[0, 0] ) mock_feature_extraction.assert_awaited_once_with("test") hf_inference_api_embedding.pooling = Pooling.MEAN with patch.object( hf_inference_api_embedding._async_client, "feature_extraction", AsyncMock(return_value=raw_single_embedding), ) as mock_feature_extraction: embedding = hf_inference_api_embedding.get_query_embedding("test") assert isinstance(embedding, list) assert len(embedding) == 1024 assert isinstance(embedding[0], float) assert np.all( np.array(embedding, dtype=raw_single_embedding.dtype) == raw_single_embedding[0].mean(axis=0) ) mock_feature_extraction.assert_awaited_once_with("test") def test_embed_query_one_dimension( self, hf_inference_api_embedding: HuggingFaceInferenceAPIEmbedding ) -> None: raw_single_embedding = np.random.default_rng().random(1024, dtype=np.float32) with patch.object( hf_inference_api_embedding._async_client, "feature_extraction", AsyncMock(return_value=raw_single_embedding), ) as mock_feature_extraction: embedding = hf_inference_api_embedding.get_query_embedding("test") assert isinstance(embedding, list) assert len(embedding) == 1024 assert isinstance(embedding[0], float) assert np.all( np.array(embedding, dtype=raw_single_embedding.dtype) == raw_single_embedding ) mock_feature_extraction.assert_awaited_once_with("test") def test_serialization( self, hf_inference_api_embedding: HuggingFaceInferenceAPIEmbedding ) -> None: serialized = hf_inference_api_embedding.to_dict() # Check Hugging Face Inference API base class specifics assert serialized["model_name"] == STUB_MODEL_NAME # Check Hugging Face Inference API Embeddings derived class specifics assert serialized["pooling"] == Pooling.CLS def test_serde( self, hf_inference_api_embedding: HuggingFaceInferenceAPIEmbedding ) -> None: serialized = hf_inference_api_embedding.model_dump() deserialized = HuggingFaceInferenceAPIEmbedding.model_validate(serialized) assert deserialized.headers == hf_inference_api_embedding.headers
TestHuggingFaceInferenceAPIEmbeddings
python
pytorch__pytorch
test/distributed/pipelining/model_registry.py
{ "start": 7366, "end": 7858 }
class ____(Function): @staticmethod def forward(ctx, input_val, weight, bias): ctx.save_for_backward(input_val, weight, bias) return input_val.mm(weight.t()) + bias @staticmethod def backward(ctx, grad_output): input_val, weight, _ = ctx.saved_tensors grad_input = grad_output.mm(weight) grad_weight = grad_output.t().mm(input_val) grad_bias = grad_output.sum(0) return grad_input, grad_weight, grad_bias
CustomLinearDxDw
python
tiangolo__fastapi
docs_src/header_param_models/tutorial002_pv1_an.py
{ "start": 158, "end": 490 }
class ____(BaseModel): class Config: extra = "forbid" host: str save_data: bool if_modified_since: Union[str, None] = None traceparent: Union[str, None] = None x_tag: List[str] = [] @app.get("/items/") async def read_items(headers: Annotated[CommonHeaders, Header()]): return headers
CommonHeaders
python
Netflix__metaflow
metaflow/plugins/env_escape/configurations/test_lib_impl/test_lib.py
{ "start": 1029, "end": 1169 }
class ____(BaseClass): def handle_endtag(self, tag): self._output.append(tag) return super().handle_endtag(tag)
ChildClass
python
ray-project__ray
rllib/connectors/common/batch_individual_items.py
{ "start": 576, "end": 8197 }
class ____(ConnectorV2): """Batches individual data-items (in lists) into tensors (with batch dimension). Note: This is one of the default env-to-module or Learner ConnectorV2 pieces that are added automatically by RLlib into every env-to-module/Learner connector pipeline, unless `config.add_default_connectors_to_env_to_module_pipeline` or `config.add_default_connectors_to_learner_pipeline ` are set to False. The default env-to-module connector pipeline is: [ [0 or more user defined ConnectorV2 pieces], AddObservationsFromEpisodesToBatch, AddTimeDimToBatchAndZeroPad, AddStatesFromEpisodesToBatch, AgentToModuleMapping, # only in multi-agent setups! BatchIndividualItems, NumpyToTensor, ] The default Learner connector pipeline is: [ [0 or more user defined ConnectorV2 pieces], AddObservationsFromEpisodesToBatch, AddColumnsFromEpisodesToTrainBatch, AddTimeDimToBatchAndZeroPad, AddStatesFromEpisodesToBatch, AgentToModuleMapping, # only in multi-agent setups! BatchIndividualItems, NumpyToTensor, ] This ConnectorV2: - Operates only on the input `data`, NOT the incoming list of episode objects (ignored). - In the single-agent case, `data` must already be a dict, structured as follows by prior connector pieces of the same pipeline: [col0] -> {[(eps_id,)]: [list of individual batch items]} - In the multi-agent case, `data` must already be a dict, structured as follows by prior connector pieces of the same pipeline (in particular the `AgentToModuleMapping` piece): [module_id] -> [col0] -> [list of individual batch items] - Translates the above data under the different columns (e.g. "obs") into final (batched) structures. For the single-agent case, the output `data` looks like this: [col0] -> [possibly complex struct of batches (at the leafs)]. For the multi-agent case, the output `data` looks like this: [module_id] -> [col0] -> [possibly complex struct of batches (at the leafs)]. .. testcode:: from ray.rllib.connectors.common import BatchIndividualItems from ray.rllib.utils.test_utils import check single_agent_batch = { "obs": { # Note that at this stage, next-obs is not part of the data anymore .. ("MA-EPS0",): [0, 1], ("MA-EPS1",): [2, 3], }, "actions": { # .. so we have as many actions per episode as we have observations. ("MA-EPS0",): [4, 5], ("MA-EPS1",): [6, 7], }, } # Create our (single-agent) connector piece. connector = BatchIndividualItems() # Call the connector (and thereby batch the individual items). output_batch = connector( rl_module=None, # This particular connector works without an RLModule. batch=single_agent_batch, episodes=[], # This particular connector works without a list of episodes. explore=True, shared_data={}, ) # `output_batch` should now be batched (episode IDs should have been removed # from the struct). check( output_batch, {"obs": [0, 1, 2, 3], "actions": [4, 5, 6, 7]}, ) """ def __init__( self, input_observation_space: Optional[gym.Space] = None, input_action_space: Optional[gym.Space] = None, *, multi_agent: bool = False, **kwargs, ): """Initializes a BatchIndividualItems instance. Args: multi_agent: Whether this is a connector operating on a multi-agent observation space mapping AgentIDs to individual agents' observations. """ super().__init__( input_observation_space=input_observation_space, input_action_space=input_action_space, **kwargs, ) self._multi_agent = multi_agent @override(ConnectorV2) def __call__( self, *, rl_module: RLModule, batch: Dict[str, Any], episodes: List[EpisodeType], explore: Optional[bool] = None, shared_data: Optional[dict] = None, **kwargs, ) -> Any: is_multi_rl_module = isinstance(rl_module, MultiRLModule) # Convert lists of individual items into properly batched data. for column, column_data in batch.copy().items(): # Multi-agent case: This connector piece should only be used after(!) # the AgentToModuleMapping connector has already been applied, leading # to a batch structure of: # [module_id] -> [col0] -> [list of individual batch items] if is_multi_rl_module and column in rl_module: # Case, in which a column has already been properly batched before this # connector piece is called. if not self._multi_agent: continue # If MA Off-Policy and independent sampling we need to overcome this # check. module_data = column_data for col, col_data in module_data.copy().items(): if isinstance(col_data, list) and col != Columns.INFOS: module_data[col] = batch_fn( col_data, individual_items_already_have_batch_dim="auto", ) # Simple case: There is a list directly under `column`: # Batch the list. elif isinstance(column_data, list): batch[column] = batch_fn( column_data, individual_items_already_have_batch_dim="auto", ) # Single-agent case: There is a dict under `column` mapping # `eps_id` to lists of items: # Concat all these lists, then batch. elif not self._multi_agent: # TODO: only really need this in non-Learner connector pipeline memorized_map_structure = [] list_to_be_batched = [] for (eps_id,) in column_data.keys(): for item in column_data[(eps_id,)]: # Only record structure for OBS column. if column == Columns.OBS: memorized_map_structure.append(eps_id) list_to_be_batched.append(item) # INFOS should not be batched (remain a list). batch[column] = ( list_to_be_batched if column == Columns.INFOS else batch_fn( list_to_be_batched, individual_items_already_have_batch_dim="auto", ) ) if is_multi_rl_module: if DEFAULT_MODULE_ID not in batch: batch[DEFAULT_MODULE_ID] = {} batch[DEFAULT_MODULE_ID][column] = batch.pop(column) # Only record structure for OBS column. if column == Columns.OBS: shared_data["memorized_map_structure"] = memorized_map_structure # Multi-agent case: But Module ID not found in our RLModule -> Ignore this # `module_id` entirely. # else: # pass return batch
BatchIndividualItems
python
jazzband__django-simple-history
simple_history/tests/admin.py
{ "start": 494, "end": 688 }
class ____(SimpleHistoryAdmin): def has_change_permission(self, request, obj=None): return False def has_view_permission(self, request, obj=None): return False
PersonAdmin
python
wireservice__csvkit
csvkit/utilities/csvpy.py
{ "start": 113, "end": 3332 }
class ____(CSVKitUtility): description = 'Load a CSV file into a CSV reader and then drop into a Python shell.' override_flags = ['l', 'zero', 'add-bom'] def add_arguments(self): self.argparser.add_argument( '--dict', dest='as_dict', action='store_true', help='Load the CSV file into a DictReader.') self.argparser.add_argument( '--agate', dest='as_agate', action='store_true', help='Load the CSV file into an agate table.') self.argparser.add_argument( '--no-number-ellipsis', dest='no_number_ellipsis', action='store_true', help='Disable the ellipsis if the max precision is exceeded.') self.argparser.add_argument( '-y', '--snifflimit', dest='sniff_limit', type=int, default=1024, help='Limit CSV dialect sniffing to the specified number of bytes. ' 'Specify "0" to disable sniffing entirely, or "-1" to sniff the entire file.') self.argparser.add_argument( '-I', '--no-inference', dest='no_inference', action='store_true', help='Disable type inference (and --locale, --date-format, --datetime-format, --no-leading-zeroes) ' 'when parsing the input.') def main(self): if self.input_file == sys.stdin: self.argparser.error('csvpy cannot accept input as piped data via STDIN.') if self.args.no_number_ellipsis: config.set_option('number_truncation_chars', '') # Attempt reading filename, will cause lazy loader to access file and raise error if it does not exist filename = self.input_file.name if self.args.as_dict: klass = agate.csv.DictReader class_name = 'agate.csv.DictReader' variable_name = 'reader' input_file = self.skip_lines() kwargs = {} elif self.args.as_agate: klass = agate.Table.from_csv class_name = 'agate.Table' variable_name = 'table' input_file = self.input_file sniff_limit = self.args.sniff_limit if self.args.sniff_limit != -1 else None kwargs = dict( skip_lines=self.args.skip_lines, sniff_limit=sniff_limit, column_types=self.get_column_types(), ) else: klass = agate.csv.reader class_name = 'agate.csv.reader' variable_name = 'reader' input_file = self.skip_lines() kwargs = {} variable = klass(input_file, **kwargs, **self.reader_kwargs) welcome_message = f'Welcome! "{filename}" has been loaded in an {class_name} object named "{variable_name}".' try: from IPython.frontend.terminal.embed import InteractiveShellEmbed exec(f'{variable_name} = variable') ipy = InteractiveShellEmbed(banner1=welcome_message) ipy() except ImportError: import code code.interact(welcome_message, local={variable_name: variable}) def launch_new_instance(): utility = CSVPy() utility.run() if __name__ == '__main__': launch_new_instance()
CSVPy
python
pytorch__pytorch
.github/scripts/convert_lintrunner_annotations_to_github.py
{ "start": 187, "end": 299 }
class ____(str, Enum): NOTICE = "notice" WARNING = "warning" FAILURE = "failure"
GitHubAnnotationLevel
python
doocs__leetcode
solution/2500-2599/2510.Check if There is a Path With Equal Number of 0's And 1's/Solution.py
{ "start": 0, "end": 555 }
class ____: def isThereAPath(self, grid: List[List[int]]) -> bool: @cache def dfs(i, j, k): if i >= m or j >= n: return False k += grid[i][j] if k > s or i + j + 1 - k > s: return False if i == m - 1 and j == n - 1: return k == s return dfs(i + 1, j, k) or dfs(i, j + 1, k) m, n = len(grid), len(grid[0]) s = m + n - 1 if s & 1: return False s >>= 1 return dfs(0, 0, 0)
Solution
python
airbytehq__airbyte
airbyte-integrations/connectors/source-slack/components.py
{ "start": 8601, "end": 9262 }
class ____(APIBudget, LimiterMixin): """ Switches to MovingWindowCallRatePolicy 1 request per minute if rate limits were exceeded. """ def update_from_response(self, request: Any, response: Any) -> None: current_policy = self.get_matching_policy(request) if response.status_code == 429 and isinstance(current_policy, UnlimitedCallRatePolicy): matchers = current_policy._matchers self._policies = [ MovingWindowCallRatePolicy( matchers=matchers, rates=[MESSAGES_AND_THREADS_RATE], ) ] @dataclass
MessagesAndThreadsApiBudget
python
Netflix__metaflow
metaflow/plugins/debug_monitor.py
{ "start": 253, "end": 1099 }
class ____(object): def __init__(self): pass def process_message(self, msg): # type: (Message) -> None if msg.msg_type == MessageTypes.MUST_SEND: print("DebugMonitor[must_send]: %s" % str(msg.payload), file=sys.stderr) elif msg.msg_type == MessageTypes.SHUTDOWN: print("DebugMonitor[shutdown]: got shutdown!", file=sys.stderr) self._shutdown() elif msg.msg_type == MessageTypes.BEST_EFFORT: for v in msg.payload.values(): metric = Metric.deserialize(v) print( "DebugMonitor[metric]: %s for %s: %s" % (metric.metric_type, metric.name, str(metric.value)), file=sys.stderr, ) def _shutdown(self): sys.stderr.flush()
DebugMonitorSidecar
python
mlflow__mlflow
mlflow/utils/autologging_utils/client.py
{ "start": 3178, "end": 15728 }
class ____: """ Efficiently implements a subset of MLflow Tracking's `MlflowClient` and fluent APIs to provide automatic batching and async execution of run operations by way of queueing, as well as parameter / tag truncation for autologging use cases. Run operations defined by this client, such as `create_run` and `log_metrics`, enqueue data for future persistence to MLflow Tracking. Data is not persisted until the queue is flushed via the `flush()` method, which supports synchronous and asynchronous execution. MlflowAutologgingQueueingClient is not threadsafe; none of its APIs should be called concurrently. """ def __init__(self, tracking_uri=None): from mlflow.tracking.client import MlflowClient self._client = MlflowClient(tracking_uri) self._pending_ops_by_run_id = {} def __enter__(self): """ Enables `MlflowAutologgingQueueingClient` to be used as a context manager with synchronous flushing upon exit, removing the need to call `flush()` for use cases where logging completion can be waited upon synchronously. Run content is only flushed if the context exited without an exception. """ return self def __exit__(self, exc_type, exc, traceback): """ Enables `MlflowAutologgingQueueingClient` to be used as a context manager with synchronous flushing upon exit, removing the need to call `flush()` for use cases where logging completion can be waited upon synchronously. Run content is only flushed if the context exited without an exception. """ # NB: Run content is only flushed upon context exit to ensure that we don't elide the # original exception thrown by the context (because `flush()` itself may throw). This # is consistent with the behavior of a routine that calls `flush()` explicitly: content # is not logged if an exception preempts the call to `flush()` if exc is None and exc_type is None and traceback is None: self.flush(synchronous=True) else: _logger.debug( "Skipping run content logging upon MlflowAutologgingQueueingClient context because" " an exception was raised within the context: %s", exc, ) def create_run( self, experiment_id: str, start_time: int | None = None, tags: dict[str, Any] | None = None, run_name: str | None = None, ) -> PendingRunId: """ Enqueues a CreateRun operation with the specified attributes, returning a `PendingRunId` instance that can be used as input to other client logging APIs (e.g. `log_metrics`, `log_params`, ...). Returns: A `PendingRunId` that can be passed as the `run_id` parameter to other client logging APIs, such as `log_params` and `log_metrics`. """ tags = tags or {} tags = _truncate_dict( tags, max_key_length=MAX_ENTITY_KEY_LENGTH, max_value_length=MAX_TAG_VAL_LENGTH ) run_id = PendingRunId() self._get_pending_operations(run_id).enqueue( create_run=_PendingCreateRun( experiment_id=experiment_id, start_time=start_time, tags=[RunTag(key, str(value)) for key, value in tags.items()], run_name=run_name, ) ) return run_id def set_terminated( self, run_id: str | PendingRunId, status: str | None = None, end_time: int | None = None, ) -> None: """ Enqueues an UpdateRun operation with the specified `status` and `end_time` attributes for the specified `run_id`. """ self._get_pending_operations(run_id).enqueue( set_terminated=_PendingSetTerminated(status=status, end_time=end_time) ) def log_params(self, run_id: str | PendingRunId, params: dict[str, Any]) -> None: """ Enqueues a collection of Parameters to be logged to the run specified by `run_id`. """ params = _truncate_dict( params, max_key_length=MAX_ENTITY_KEY_LENGTH, max_value_length=MAX_PARAM_VAL_LENGTH ) params_arr = [Param(key, str(value)) for key, value in params.items()] self._get_pending_operations(run_id).enqueue(params=params_arr) def log_inputs(self, run_id: str | PendingRunId, datasets: list[DatasetInput] | None) -> None: """ Enqueues a collection of Dataset to be logged to the run specified by `run_id`. """ if datasets is None or len(datasets) == 0: return self._get_pending_operations(run_id).enqueue(datasets=datasets) def log_metrics( self, run_id: str | PendingRunId, metrics: dict[str, float], step: int | None = None, dataset: Optional["Dataset"] = None, model_id: str | None = None, ) -> None: """ Enqueues a collection of Metrics to be logged to the run specified by `run_id` at the step specified by `step`. """ metrics = _truncate_dict(metrics, max_key_length=MAX_ENTITY_KEY_LENGTH) timestamp_ms = get_current_time_millis() metrics_arr = [ Metric( key, value, timestamp_ms, step or 0, model_id=model_id, dataset_name=dataset and dataset.name, dataset_digest=dataset and dataset.digest, ) for key, value in metrics.items() ] self._get_pending_operations(run_id).enqueue(metrics=metrics_arr) def set_tags(self, run_id: str | PendingRunId, tags: dict[str, Any]) -> None: """ Enqueues a collection of Tags to be logged to the run specified by `run_id`. """ tags = _truncate_dict( tags, max_key_length=MAX_ENTITY_KEY_LENGTH, max_value_length=MAX_TAG_VAL_LENGTH ) tags_arr = [RunTag(key, str(value)) for key, value in tags.items()] self._get_pending_operations(run_id).enqueue(tags=tags_arr) def flush(self, synchronous=True): """ Flushes all queued run operations, resulting in the creation or mutation of runs and run data. Args: synchronous: If `True`, run operations are performed synchronously, and a `RunOperations` result object is only returned once all operations are complete. If `False`, run operations are performed asynchronously, and an `RunOperations` object is returned that represents the ongoing run operations. Returns: A `RunOperations` instance representing the flushed operations. These operations are already complete if `synchronous` is `True`. If `synchronous` is `False`, these operations may still be inflight. Operation completion can be synchronously waited on via `RunOperations.await_completion()`. """ logging_futures = [ _AUTOLOGGING_QUEUEING_CLIENT_THREAD_POOL.submit( self._flush_pending_operations, pending_operations=pending_operations, ) for pending_operations in self._pending_ops_by_run_id.values() ] self._pending_ops_by_run_id = {} logging_operations = RunOperations(logging_futures) if synchronous: logging_operations.await_completion() return logging_operations def _get_pending_operations(self, run_id): """ Returns: A `_PendingRunOperations` containing all pending operations for the specified `run_id`. """ if run_id not in self._pending_ops_by_run_id: self._pending_ops_by_run_id[run_id] = _PendingRunOperations(run_id=run_id) return self._pending_ops_by_run_id[run_id] def _try_operation(self, fn, *args, **kwargs): """ Attempt to evaluate the specified function, `fn`, on the specified `*args` and `**kwargs`, returning either the result of the function evaluation (if evaluation was successful) or the exception raised by the function evaluation (if evaluation was unsuccessful). """ try: return fn(*args, **kwargs) except Exception as e: return e def _flush_pending_operations(self, pending_operations): """ Synchronously and sequentially flushes the specified list of pending run operations. NB: Operations are not parallelized on a per-run basis because MLflow's File Store, which is frequently used for local ML development, does not support threadsafe metadata logging within a given run. """ if pending_operations.create_run: create_run_tags = pending_operations.create_run.tags num_additional_tags_to_include_during_creation = MAX_ENTITIES_PER_BATCH - len( create_run_tags ) if num_additional_tags_to_include_during_creation > 0: create_run_tags.extend( pending_operations.tags_queue[:num_additional_tags_to_include_during_creation] ) pending_operations.tags_queue = pending_operations.tags_queue[ num_additional_tags_to_include_during_creation: ] new_run = self._client.create_run( experiment_id=pending_operations.create_run.experiment_id, start_time=pending_operations.create_run.start_time, tags={tag.key: tag.value for tag in create_run_tags}, ) pending_operations.run_id = new_run.info.run_id run_id = pending_operations.run_id assert not isinstance(run_id, PendingRunId), "Run ID cannot be pending for logging" operation_results = [] param_batches_to_log = chunk_list( pending_operations.params_queue, chunk_size=MAX_PARAMS_TAGS_PER_BATCH, ) tag_batches_to_log = chunk_list( pending_operations.tags_queue, chunk_size=MAX_PARAMS_TAGS_PER_BATCH, ) for params_batch, tags_batch in zip_longest( param_batches_to_log, tag_batches_to_log, fillvalue=[] ): metrics_batch_size = min( MAX_ENTITIES_PER_BATCH - len(params_batch) - len(tags_batch), MAX_METRICS_PER_BATCH, ) metrics_batch_size = max(metrics_batch_size, 0) metrics_batch = pending_operations.metrics_queue[:metrics_batch_size] pending_operations.metrics_queue = pending_operations.metrics_queue[metrics_batch_size:] operation_results.append( self._try_operation( self._client.log_batch, run_id=run_id, metrics=metrics_batch, params=params_batch, tags=tags_batch, ) ) operation_results.extend( self._try_operation(self._client.log_batch, run_id=run_id, metrics=metrics_batch) for metrics_batch in chunk_list( pending_operations.metrics_queue, chunk_size=MAX_METRICS_PER_BATCH ) ) operation_results.extend( self._try_operation(self._client.log_inputs, run_id=run_id, datasets=datasets_batch) for datasets_batch in chunk_list( pending_operations.datasets_queue, chunk_size=MAX_DATASETS_PER_BATCH ) ) if pending_operations.set_terminated: operation_results.append( self._try_operation( self._client.set_terminated, run_id=run_id, status=pending_operations.set_terminated.status, end_time=pending_operations.set_terminated.end_time, ) ) failures = [result for result in operation_results if isinstance(result, Exception)] if len(failures) > 0: raise MlflowException( message=( f"Failed to perform one or more operations on the run with ID {run_id}." f" Failed operations: {failures}" ) )
MlflowAutologgingQueueingClient
python
huggingface__transformers
tests/models/nougat/test_tokenization_nougat.py
{ "start": 6014, "end": 13740 }
class ____(unittest.TestCase): def setUp(self): super().setUp() self.tokenizer = NougatTokenizer.from_pretrained("facebook/nougat-base") def test_correct_tables_basic(self): input_str = "\\begin{table} \\begin{tabular}{l l} & \\ \\end{tabular} \\end{table}" expected_output = "\\begin{table}\n\\begin{tabular}{l l} & \\ \\end{tabular}\n\\end{table}" self.assertEqual(self.tokenizer.correct_tables(input_str), expected_output) def test_correct_tables_high_count(self): input_str = "\\begin{tabular}" * 20 expected_output = "" self.assertEqual(self.tokenizer.correct_tables(input_str), expected_output) @require_levenshtein @require_nltk def test_postprocess_as_nougat_no_markdown(self): input_str = "# Nougat: Neural Optical Understanding for Academic Documents\n\n Lukas Blecher\n\nCorrespondence to: lblecher@meta.com\n\nGuillem Cucurull\n\nThomas Scialom\n\nRobert Stojnic\n\nMeta AI\n\nThe paper reports 8.1M papers but the authors recently updated the numbers on the GitHub page https://github.com/allenai/s2orc\n\n###### Abstract\n\nScientific knowledge is predominantly stored in books and scientific journals, often in the form of PDFs. However, the PDF format leads to a loss of semantic information, particularly for mathematical expressions. We propose Nougat (**N**eural **O**ptical **U**nderstanding for **A**cademic Documents), a Visual Transformer model that performs an _Optical Character Recognition_ (OCR) task for processing scientific documents into a markup language, and demonstrate the effectiveness of our model on a new dataset of scientific documents. The proposed approach offers a promising solution to enhance the accessibility of scientific knowledge in the digital age, by bridging the gap between human-readable documents and machine-readable text. We release the models and code to accelerate future work on scientific text recognition.\n\n## 1 Introduction\n\nThe majority of scientific knowledge is stored in books or published in scientific journals, most commonly in the Portable Document Format (PDF). Next to HTML, PDFs are the second most prominent data format on the internet, making up 2.4% of common crawl [1]. However, the information stored in these files is very difficult to extract into any other formats. This is especially true for highly specialized documents, such as scientific research papers, where the semantic information of mathematical expressions is lost.\n\nExisting Optical Character Recognition (OCR) engines, such as Tesseract OCR [2], excel at detecting and classifying individual characters and words in an image, but fail to understand the relationship between them due to their line-by-line approach. This means that they treat superscripts and subscripts in the same way as the surrounding text, which is a significant drawback for mathematical expressions. In mathematical notations like fractions, exponents, and matrices, relative positions of characters are crucial.\n\nConverting academic research papers into machine-readable text also enables accessibility and searchability of science as a whole. The information of millions of academic papers can not be fully accessed because they are locked behind an unreadable format. Existing corpora, such as the S2ORC dataset [3], capture the text of 12M2 papers using GROBID [4], but are missing meaningful representations of the mathematical equations.\n\nFootnote 2: The paper reports 8.1M papers but the authors recently updated the numbers on the GitHub page https://github.com/allenai/s2orc\n\nTo this end, we introduce Nougat, a transformer based model that can convert images of document pages to formatted markup text.\n\nThe primary contributions in this paper are\n\n* Release of a pre-trained model capable of converting a PDF to a lightweight markup language. We release the code and the model on GitHub3 Footnote 3: https://github.com/facebookresearch/nougat\n* We introduce a pipeline to create dataset for pairing PDFs to source code\n* Our method is only dependent on the image of a page, allowing access to scanned papers and books" # noqa: E231 expected_output = "\n\n# Nougat: Neural Optical Understanding for Academic Documents\n\n Lukas Blecher\n\nCorrespondence to: lblecher@meta.com\n\nGuillem Cucurull\n\nThomas Scialom\n\nRobert Stojnic\n\nMeta AI\n\nThe paper reports 8.1M papers but the authors recently updated the numbers on the GitHub page https://github.com/allenai/s2orc\n\n###### Abstract\n\nScientific knowledge is predominantly stored in books and scientific journals, often in the form of PDFs. However, the PDF format leads to a loss of semantic information, particularly for mathematical expressions. We propose Nougat (**N**eural **O**ptical **U**nderstanding for **A**cademic Documents), a Visual Transformer model that performs an _Optical Character Recognition_ (OCR) task for processing scientific documents into a markup language, and demonstrate the effectiveness of our model on a new dataset of scientific documents. The proposed approach offers a promising solution to enhance the accessibility of scientific knowledge in the digital age, by bridging the gap between human-readable documents and machine-readable text. We release the models and code to accelerate future work on scientific text recognition.\n\n## 1 Introduction\n\nThe majority of scientific knowledge is stored in books or published in scientific journals, most commonly in the Portable Document Format (PDF). Next to HTML, PDFs are the second most prominent data format on the internet, making up 2.4% of common crawl [1]. However, the information stored in these files is very difficult to extract into any other formats. This is especially true for highly specialized documents, such as scientific research papers, where the semantic information of mathematical expressions is lost.\n\nExisting Optical Character Recognition (OCR) engines, such as Tesseract OCR [2], excel at detecting and classifying individual characters and words in an image, but fail to understand the relationship between them due to their line-by-line approach. This means that they treat superscripts and subscripts in the same way as the surrounding text, which is a significant drawback for mathematical expressions. In mathematical notations like fractions, exponents, and matrices, relative positions of characters are crucial.\n\nConverting academic research papers into machine-readable text also enables accessibility and searchability of science as a whole. The information of millions of academic papers can not be fully accessed because they are locked behind an unreadable format. Existing corpora, such as the S2ORC dataset [3], capture the text of 12M2 papers using GROBID [4], but are missing meaningful representations of the mathematical equations.\n\nFootnote 2: The paper reports 8.1M papers but the authors recently updated the numbers on the GitHub page https://github.com/allenai/s2orc\n\nTo this end, we introduce Nougat, a transformer based model that can convert images of document pages to formatted markup text.\n\nThe primary contributions in this paper are\n\n* Release of a pre-trained model capable of converting a PDF to a lightweight markup language. We release the code and the model on GitHub3 Footnote 3: https://github.com/facebookresearch/nougat\n* We introduce a pipeline to create dataset for pairing PDFs to source code\n* Our method is only dependent on the image of a page, allowing access to scanned papers and books" # noqa: E231 self.assertEqual(self.tokenizer.post_process_single(input_str, fix_markdown=False), expected_output)
NougatPostProcessingTest
python
numba__numba
numba/np/ufunc/ufunc_base.py
{ "start": 585, "end": 3335 }
class ____: @property def nin(self): return self.ufunc.nin @property def nout(self): return self.ufunc.nout @property def nargs(self): return self.ufunc.nargs @property def ntypes(self): return self.ufunc.ntypes @property def types(self): return self.ufunc.types @property def identity(self): return self.ufunc.identity @property def signature(self): return self.ufunc.signature @property def accumulate(self): return self.ufunc.accumulate @property def at(self): return self.ufunc.at @property def outer(self): return self.ufunc.outer @property def reduce(self): return self.ufunc.reduce @property def reduceat(self): return self.ufunc.reduceat def disable_compile(self): """ Disable the compilation of new signatures at call time. """ # If disabling compilation then there must be at least one signature assert len(self._dispatcher.overloads) > 0 self._frozen = True def _install_cg(self, targetctx=None): """ Install an implementation function for a GUFunc/DUFunc object in the given target context. If no target context is given, then _install_cg() installs into the target context of the dispatcher object (should be same default context used by jit() and njit()). """ if targetctx is None: targetctx = self._dispatcher.targetdescr.target_context _any = types.Any _arr = types.Array # Either all outputs are explicit or none of them are sig0 = (_any,) * self.ufunc.nin + (_arr,) * self.ufunc.nout sig1 = (_any,) * self.ufunc.nin targetctx.insert_func_defn( [(self._lower_me, self, sig) for sig in (sig0, sig1)]) def find_ewise_function(self, ewise_types): """ Given a tuple of element-wise argument types, find a matching signature in the dispatcher. Return a 2-tuple containing the matching signature, and compilation result. Will return two None's if no matching signature was found. """ if self._frozen: # If we cannot compile, coerce to the best matching loop loop = numpy_support.ufunc_find_matching_loop(self, ewise_types) if loop is None: return None, None ewise_types = tuple(loop.inputs + loop.outputs)[:len(ewise_types)] for sig, cres in self._dispatcher.overloads.items(): if self.match_signature(ewise_types, sig): return sig, cres return None, None
UfuncBase
python
pytorch__pytorch
test/inductor/test_triton_heuristics.py
{ "start": 9744, "end": 12803 }
class ____(TestCase): # Our tensor is large enough. If a unexpected copy happens, the # peak memory increase should be larger than tolerance and the test # will fail. MEM_TOLERANCE = int(256 * 1e6) def _create_caching_autotuner(self): args = TestTritonHeuristics._get_cos_kernel_caching_autotuner_args() args["optimize_mem"] = True args["mutated_arg_names"] = ["in_ptr0"] autotuner = CachingAutotuner(**args) return autotuner def _create_tensor(self, pad=1, with_offset=False): """ Create a GPU tensor of about 1GB size. """ M = 2 N = 2**29 // 4 out = rand_strided((M, N), (N + pad, 1), device=GPU_TYPE) if with_offset: out = out[:, 1:] return out def _do_test(self, gpu_tensor): torch.get_device_module(GPU_TYPE).reset_peak_memory_stats() autotuner = self._create_caching_autotuner() old_storage_offset = gpu_tensor.storage_offset() gpu_tensor_clone = clone_preserve_strides(gpu_tensor) peak_mem_before = torch.cuda.max_memory_allocated() cpu_copies = autotuner.copy_args_to_cpu_if_needed(gpu_tensor) self.assertTrue(len(cpu_copies) == 1) # Mutate the arg gpu_tensor.add_(1) # will restore gpu_tensor autotuner.restore_args_from_cpu(cpu_copies) self.assertTrue(gpu_tensor is not gpu_tensor_clone) self.assertEqual(gpu_tensor.size(), gpu_tensor_clone.size()) self.assertEqual(gpu_tensor.stride(), gpu_tensor_clone.stride()) self.assertEqual(gpu_tensor.storage_offset(), old_storage_offset) # Note: torch.allclose somehow allocates large amount of extra memory. # Record peak memory before that. peak_mem_after = torch.get_device_module(GPU_TYPE).max_memory_allocated() self.assertTrue(torch.allclose(gpu_tensor, gpu_tensor_clone)) self.assertTrue( peak_mem_after <= peak_mem_before + self.MEM_TOLERANCE, f"{peak_mem_before=} v.s. {peak_mem_after=}", ) # Avoid OOM in CI self.assertTrue(peak_mem_after < 1e10) @requires_cuda_with_enough_memory(1e10) def test_clone_contiguous_args(self): arg = self._create_tensor(pad=0) self.assertTrue(arg.is_contiguous()) self.assertTrue(arg.storage_offset() == 0) self._do_test(arg) @requires_cuda_with_enough_memory(1e10) def test_clone_non_contiguous_args(self): arg = self._create_tensor(pad=1) self.assertFalse(arg.is_contiguous()) self.assertTrue(arg.storage_offset() == 0) self._do_test(arg) @requires_cuda_with_enough_memory(1e10) def test_clone_args_with_non_zero_offset(self): arg = self._create_tensor(pad=1, with_offset=True) self.assertFalse(arg.is_contiguous()) self.assertTrue(arg.storage_offset() > 0) self._do_test(arg) if __name__ == "__main__": if IS_LINUX and HAS_GPU: run_tests()
TestArgumentCloneAndRestore
python
huggingface__transformers
tests/models/vaultgemma/test_modeling_vaultgemma.py
{ "start": 1794, "end": 12369 }
class ____(unittest.TestCase): input_text = ["Hello I am doing", "Hi today"] def setUp(self): cleanup(torch_device, gc_collect=True) def tearDown(self): cleanup(torch_device, gc_collect=True) @require_read_token def test_model_bf16(self): model_id = "google/vaultgemma-1b" EXPECTED_TEXTS = [ "<bos>Hello I am doing a project on a 1990 240sx. I have a 1", "<pad><pad><bos>Hi today I am going to show you how to make a simple 3D model of a 3D", ] model = AutoModelForCausalLM.from_pretrained(model_id, dtype=torch.bfloat16, attn_implementation="eager").to( torch_device ) tokenizer = AutoTokenizer.from_pretrained(model_id) inputs = tokenizer(self.input_text, return_tensors="pt", padding=True).to(torch_device) output = model.generate(**inputs, max_new_tokens=20, do_sample=False) output_text = tokenizer.batch_decode(output, skip_special_tokens=False) self.assertEqual(output_text, EXPECTED_TEXTS) @require_read_token def test_model_pipeline_bf16(self): model_id = "google/vaultgemma-1b" # EXPECTED_TEXTS should match the same non-pipeline test, minus the special tokens EXPECTED_TEXTS = [ "Hello I am doing a project on a 1990 240sx. I have a 1", "Hi today I am going to show you how to make a simple 3D model of a 3D", ] model = AutoModelForCausalLM.from_pretrained(model_id, dtype=torch.bfloat16).to(torch_device) tokenizer = AutoTokenizer.from_pretrained(model_id) pipe = pipeline("text-generation", model=model, tokenizer=tokenizer) output = pipe(self.input_text, max_new_tokens=20, do_sample=False, padding=True) self.assertEqual(output[0][0]["generated_text"], EXPECTED_TEXTS[0]) self.assertEqual(output[1][0]["generated_text"], EXPECTED_TEXTS[1]) @pytest.mark.torch_export_test @slow @require_read_token def test_export_static_cache(self): if version.parse(torch.__version__) < version.parse("2.5.0"): self.skipTest(reason="This test requires torch >= 2.5 to run.") from transformers.integrations.executorch import ( TorchExportableModuleWithStaticCache, ) model_id = "google/vaultgemma-1b" tokenizer = AutoTokenizer.from_pretrained(model_id, pad_token="</s>", padding_side="right") EXPECTED_TEXT_COMPLETIONS = Expectations( { ("cuda", 8): ["Hello I am doing a project on a 1990 240sx. I have a 1"], } ) EXPECTED_TEXT_COMPLETION = EXPECTED_TEXT_COMPLETIONS.get_expectation() max_generation_length = tokenizer(EXPECTED_TEXT_COMPLETION, return_tensors="pt", padding=True)[ "input_ids" ].shape[-1] # Load model device = "cpu" # TODO (joao / export experts): should be on `torch_device`, but causes GPU OOM dtype = torch.bfloat16 cache_implementation = "static" attn_implementation = "sdpa" batch_size = 1 model = AutoModelForCausalLM.from_pretrained( model_id, device_map=device, dtype=dtype, attn_implementation=attn_implementation, generation_config=GenerationConfig( use_cache=True, cache_implementation=cache_implementation, max_length=max_generation_length, cache_config={ "batch_size": batch_size, "max_cache_len": max_generation_length, }, ), ) prompts = ["Hello I am doing"] prompt_tokens = tokenizer(prompts, return_tensors="pt", padding=True).to(model.device) prompt_token_ids = prompt_tokens["input_ids"] max_new_tokens = max_generation_length - prompt_token_ids.shape[-1] # Static Cache + export from transformers.integrations.executorch import TorchExportableModuleForDecoderOnlyLM exportable_module = TorchExportableModuleForDecoderOnlyLM(model) exported_program = exportable_module.export( input_ids=torch.tensor([[1]], dtype=torch.long, device=model.device), cache_position=torch.tensor([0], dtype=torch.long, device=model.device), ) ep_generated_ids = TorchExportableModuleWithStaticCache.generate( exported_program=exported_program, prompt_token_ids=prompt_token_ids, max_new_tokens=max_new_tokens ) ep_generated_text = tokenizer.batch_decode(ep_generated_ids, skip_special_tokens=True) self.assertEqual(EXPECTED_TEXT_COMPLETION, ep_generated_text) @parameterized.expand([("flash_attention_2",), ("sdpa",), ("flex_attention",), ("eager",)]) @require_read_token def test_generation_beyond_sliding_window(self, attn_implementation: str): """Test that we can correctly generate beyond the sliding window. This is non trivial as we need to correctly slice the attention mask in all cases (because we use a hybrid cache). Outputs for every attention functions should be coherent and identical. """ # Impossible to test it with this model (even with < 100 tokens), probably due to the compilation of a large model. if attn_implementation == "flex_attention": self.skipTest( reason="`flex_attention` gives `torch._inductor.exc.InductorError: RuntimeError: No valid triton configs. OutOfMemoryError: out of resource: triton_tem_fused_0 Required: 147456 Hardware limit:101376 Reducing block sizes or `num_stages` may help.`" ) if attn_implementation == "flash_attention_2" and not is_flash_attn_2_available(): self.skipTest("FlashAttention2 is required for this test.") if torch_device == "xpu" and attn_implementation == "flash_attention_2": self.skipTest(reason="Intel XPU doesn't support flash_attention_2 as of now.") model_id = "google/vaultgemma-1b" EXPECTED_COMPLETIONS = [ " place pretty place pretty place. place pretty place pretty place. place pretty place pretty place. place pretty", ", green, yellow, orange, purple, black, white, and gray.\n\nA list of", ] input_text = [ "This is a nice place. " * 800 + "I really enjoy the scenery,", # This is larger than 4096 tokens "A list of colors: red, blue", # This will almost all be padding tokens ] tokenizer = AutoTokenizer.from_pretrained(model_id, padding="left") inputs = tokenizer(input_text, padding=True, return_tensors="pt").to(torch_device) model = AutoModelForCausalLM.from_pretrained( model_id, attn_implementation=attn_implementation, dtype=torch.float16 ).to(torch_device) # Make sure prefill is larger than sliding window input_size = inputs.input_ids.shape[-1] self.assertTrue(input_size > model.config.sliding_window) # It should by Hybrid by default from hub config, but let's make sure! out = model.generate(**inputs, max_new_tokens=20, cache_implementation="hybrid")[:, input_size:] output_text = tokenizer.batch_decode(out) self.assertEqual(output_text, EXPECTED_COMPLETIONS) @parameterized.expand([("flash_attention_2",), ("sdpa",), ("flex_attention",), ("eager",)]) @require_read_token def test_generation_beyond_sliding_window_dynamic(self, attn_implementation: str): """ Same as above, but explicitly setting the cache to Dynamic, as it's otherwise static by default for the model on the hub """ # Impossible to test it with this model (even with < 100 tokens), probably due to the compilation of a large model. if attn_implementation == "flex_attention": self.skipTest( reason="`flex_attention` gives `torch._inductor.exc.InductorError: RuntimeError: No valid triton configs. OutOfMemoryError: out of resource: triton_tem_fused_0 Required: 147456 Hardware limit:101376 Reducing block sizes or `num_stages` may help.`" ) if attn_implementation == "flash_attention_2" and not is_flash_attn_2_available(): self.skipTest("FlashAttention2 is required for this test.") if torch_device == "xpu" and attn_implementation == "flash_attention_2": self.skipTest(reason="Intel XPU doesn't support flash_attention_2 as of now.") model_id = "google/vaultgemma-1b" EXPECTED_COMPLETIONS = [ " place pretty place pretty place. place pretty place pretty place. place pretty place pretty place. place pretty", ", green, yellow, orange, purple, black, white, and gray.\n\nA list of", ] input_text = [ "This is a nice place. " * 800 + "I really enjoy the scenery,", # This is larger than 4096 tokens "A list of colors: red, blue", # This will almost all be padding tokens ] tokenizer = AutoTokenizer.from_pretrained(model_id, padding="left") inputs = tokenizer(input_text, padding=True, return_tensors="pt").to(torch_device) model = AutoModelForCausalLM.from_pretrained( model_id, attn_implementation=attn_implementation, dtype=torch.float16 ).to(torch_device) # Make sure prefill is larger than sliding window input_size = inputs.input_ids.shape[-1] self.assertTrue(input_size > model.config.sliding_window) out = model.generate(**inputs, max_new_tokens=20, cache_implementation="dynamic", return_dict_in_generate=True) output_text = tokenizer.batch_decode(out.sequences[:, input_size:]) self.assertEqual(output_text, EXPECTED_COMPLETIONS) # Let's check that the dynamic cache has hybrid layers! dynamic_cache = out.past_key_values self.assertTrue(isinstance(dynamic_cache, DynamicCache)) for layer, layer_type in zip(dynamic_cache.layers, model.config.layer_types): if layer_type == "sliding_attention": self.assertTrue(isinstance(layer, DynamicSlidingWindowLayer)) self.assertEqual(layer.keys.shape[-2], model.config.sliding_window - 1) else: self.assertTrue(isinstance(layer, DynamicLayer)) # max_new_tokens - 1 because last token generated is not cached self.assertEqual(layer.keys.shape[-2], input_size + 20 - 1)
VaultGemmaIntegrationTest
python
ansible__ansible
lib/ansible/module_utils/facts/network/dragonfly.py
{ "start": 1035, "end": 1149 }
class ____(NetworkCollector): _fact_class = DragonFlyNetwork _platform = 'DragonFly'
DragonFlyNetworkCollector
python
huggingface__transformers
src/transformers/models/bert/modeling_bert.py
{ "start": 42634, "end": 45978 }
class ____(BertPreTrainedModel): def __init__(self, config): super().__init__(config) self.bert = BertModel(config) self.cls = BertOnlyNSPHead(config) # Initialize weights and apply final processing self.post_init() @can_return_tuple @auto_docstring def forward( self, input_ids: Optional[torch.Tensor] = None, attention_mask: Optional[torch.Tensor] = None, token_type_ids: Optional[torch.Tensor] = None, position_ids: Optional[torch.Tensor] = None, inputs_embeds: Optional[torch.Tensor] = None, labels: Optional[torch.Tensor] = None, **kwargs: Unpack[TransformersKwargs], ) -> Union[tuple[torch.Tensor], NextSentencePredictorOutput]: r""" labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): Labels for computing the next sequence prediction (classification) loss. Input should be a sequence pair (see `input_ids` docstring). Indices should be in `[0, 1]`: - 0 indicates sequence B is a continuation of sequence A, - 1 indicates sequence B is a random sequence. Example: ```python >>> from transformers import AutoTokenizer, BertForNextSentencePrediction >>> import torch >>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased") >>> model = BertForNextSentencePrediction.from_pretrained("google-bert/bert-base-uncased") >>> prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced." >>> next_sentence = "The sky is blue due to the shorter wavelength of blue light." >>> encoding = tokenizer(prompt, next_sentence, return_tensors="pt") >>> outputs = model(**encoding, labels=torch.LongTensor([1])) >>> logits = outputs.logits >>> assert logits[0, 0] < logits[0, 1] # next sentence was random ``` """ if "next_sentence_label" in kwargs: warnings.warn( "The `next_sentence_label` argument is deprecated and will be removed in a future version, use" " `labels` instead.", FutureWarning, ) labels = kwargs.pop("next_sentence_label") outputs = self.bert( input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, inputs_embeds=inputs_embeds, return_dict=True, **kwargs, ) pooled_output = outputs[1] seq_relationship_scores = self.cls(pooled_output) next_sentence_loss = None if labels is not None: loss_fct = CrossEntropyLoss() next_sentence_loss = loss_fct(seq_relationship_scores.view(-1, 2), labels.view(-1)) return NextSentencePredictorOutput( loss=next_sentence_loss, logits=seq_relationship_scores, hidden_states=outputs.hidden_states, attentions=outputs.attentions, ) @auto_docstring( custom_intro=""" Bert Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output) e.g. for GLUE tasks. """ )
BertForNextSentencePrediction
python
kamyu104__LeetCode-Solutions
Python/find-n-unique-integers-sum-up-to-zero.py
{ "start": 29, "end": 231 }
class ____(object): def sumZero(self, n): """ :type n: int :rtype: List[int] """ return [i for i in xrange(-(n//2), n//2+1) if not (i == 0 and n%2 == 0)]
Solution
python
huggingface__transformers
src/transformers/models/diffllama/modeling_diffllama.py
{ "start": 35061, "end": 35174 }
class ____(GenericForSequenceClassification, DiffLlamaPreTrainedModel): pass
DiffLlamaForSequenceClassification
python
tensorflow__tensorflow
tensorflow/python/profiler/profiler_v2_test.py
{ "start": 1093, "end": 3585 }
class ____(test_util.TensorFlowTestCase): def test_profile_exceptions(self): logdir = self.get_temp_dir() profiler.start(logdir) with self.assertRaises(errors.AlreadyExistsError): profiler.start(logdir) profiler.stop() with self.assertRaises(errors.UnavailableError): profiler.stop() # Test with a bad logdir, and it correctly raises exception and deletes # profiler. # pylint: disable=anomalous-backslash-in-string profiler.start('/dev/null/\/\/:123') # pylint: enable=anomalous-backslash-in-string with self.assertRaises(Exception): profiler.stop() profiler.start(logdir) profiler.stop() def test_save_profile(self): logdir = self.get_temp_dir() profiler.start(logdir) with trace.Trace('three_times_five'): three = constant_op.constant(3) five = constant_op.constant(5) product = three * five self.assertAllEqual(15, product) profiler.stop() file_list = gfile.ListDirectory(logdir) self.assertEqual(len(file_list), 1) for file_name in gfile.ListDirectory(logdir): if gfile.IsDirectory(os.path.join(logdir, file_name)): self.assertEqual(file_name, 'plugins') profile_dir = os.path.join(logdir, 'plugins', 'profile') run = gfile.ListDirectory(profile_dir)[0] hostname = socket.gethostname() xplane = os.path.join(profile_dir, run, hostname + '.xplane.pb') self.assertTrue(gfile.Exists(xplane)) def test_profile_with_options(self): logdir = self.get_temp_dir() options = profiler.ProfilerOptions( host_tracer_level=3, python_tracer_level=1) profiler.start(logdir, options) with trace.Trace('three_times_five'): three = constant_op.constant(3) five = constant_op.constant(5) product = three * five self.assertAllEqual(15, product) profiler.stop() file_list = gfile.ListDirectory(logdir) self.assertEqual(len(file_list), 1) def test_context_manager_with_options(self): logdir = self.get_temp_dir() options = profiler.ProfilerOptions( host_tracer_level=3, python_tracer_level=1) with profiler.Profile(logdir, options): with trace.Trace('three_times_five'): three = constant_op.constant(3) five = constant_op.constant(5) product = three * five self.assertAllEqual(15, product) file_list = gfile.ListDirectory(logdir) self.assertEqual(len(file_list), 1) if __name__ == '__main__': test.main()
ProfilerTest
python
huggingface__transformers
src/transformers/models/groupvit/modeling_groupvit.py
{ "start": 19186, "end": 22547 }
class ____(nn.Module): """This corresponds to the `GroupingLayer` class in the GroupViT implementation.""" def __init__( self, config: GroupViTVisionConfig, depth: int, num_prev_group_token: int, num_group_token: int, num_output_group: int, ): super().__init__() self.depth = depth self.num_group_token = num_group_token if num_group_token > 0: self.group_token = nn.Parameter(torch.zeros(1, num_group_token, config.hidden_size)) else: self.group_token = None self.layers = nn.ModuleList([GroupViTEncoderLayer(config) for _ in range(depth)]) if num_group_token > 0: self.downsample = GroupViTTokenAssign( config=config, num_group_token=num_group_token, num_output_group=num_output_group, ) else: self.downsample = None if num_prev_group_token > 0 and num_group_token > 0: self.group_projector = nn.Sequential( nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps), GroupViTMixerMLP(config, num_prev_group_token, config.hidden_size // 2, num_group_token), ) else: self.group_projector = None @property def with_group_token(self): return self.group_token is not None def split_x(self, x): if self.with_group_token: return x[:, : -self.num_group_token], x[:, -self.num_group_token :] else: return x, None def concat_x(self, x: torch.Tensor, group_token: Optional[torch.Tensor] = None) -> torch.Tensor: if group_token is None: return x return torch.cat([x, group_token], dim=1) def forward( self, hidden_states: torch.Tensor, prev_group_token: Optional[torch.Tensor] = None, output_attentions: Optional[bool] = False, ) -> tuple[torch.FloatTensor]: """ Args: hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)` attention_mask (`torch.FloatTensor`): attention mask of size `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values. `(config.encoder_attention_heads,)`. output_attentions (`bool`, *optional*): Whether or not to return the grouping tensors of Grouping block. """ if self.with_group_token: group_token = self.group_token.expand(hidden_states.size(0), -1, -1) if self.group_projector is not None: group_token = group_token + self.group_projector(prev_group_token) else: group_token = None x = hidden_states cat_x = self.concat_x(x, group_token) for layer in self.layers: layer_out = layer(cat_x, attention_mask=None, causal_attention_mask=None) cat_x = layer_out[0] x, group_token = self.split_x(cat_x) attention = None if self.downsample is not None: x, attention = self.downsample(x, group_token) outputs = (x, group_token) if output_attentions: outputs = outputs + (attention,) return outputs
GroupViTStage
python
numba__numba
numba/cuda/tests/cudapy/test_inspect.py
{ "start": 347, "end": 5196 }
class ____(CUDATestCase): @property def cc(self): return cuda.current_context().device.compute_capability def test_monotyped(self): sig = (float32, int32) @cuda.jit(sig) def foo(x, y): pass file = StringIO() foo.inspect_types(file=file) typeanno = file.getvalue() # Function name in annotation self.assertIn("foo", typeanno) # Signature in annotation self.assertIn("(float32, int32)", typeanno) file.close() # Function name in LLVM llvm = foo.inspect_llvm(sig) self.assertIn("foo", llvm) # Kernel in LLVM self.assertIn('cuda.kernel.wrapper', llvm) # Wrapped device function body in LLVM self.assertIn("define linkonce_odr i32", llvm) asm = foo.inspect_asm(sig) # Function name in PTX self.assertIn("foo", asm) # NVVM inserted comments in PTX self.assertIn("Generated by NVIDIA NVVM Compiler", asm) def test_polytyped(self): @cuda.jit def foo(x, y): pass foo[1, 1](1, 1) foo[1, 1](1.2, 2.4) file = StringIO() foo.inspect_types(file=file) typeanno = file.getvalue() file.close() # Signature in annotation self.assertIn("({0}, {0})".format(intp), typeanno) self.assertIn("(float64, float64)", typeanno) # Signature in LLVM dict llvmirs = foo.inspect_llvm() self.assertEqual(2, len(llvmirs), ) self.assertIn((intp, intp), llvmirs) self.assertIn((float64, float64), llvmirs) # Function name in LLVM self.assertIn("foo", llvmirs[intp, intp]) self.assertIn("foo", llvmirs[float64, float64]) # Kernels in LLVM self.assertIn('cuda.kernel.wrapper', llvmirs[intp, intp]) self.assertIn('cuda.kernel.wrapper', llvmirs[float64, float64]) # Wrapped device function bodies in LLVM self.assertIn("define linkonce_odr i32", llvmirs[intp, intp]) self.assertIn("define linkonce_odr i32", llvmirs[float64, float64]) asmdict = foo.inspect_asm() # Signature in assembly dict self.assertEqual(2, len(asmdict), ) self.assertIn((intp, intp), asmdict) self.assertIn((float64, float64), asmdict) # NVVM inserted in PTX self.assertIn("foo", asmdict[intp, intp]) self.assertIn("foo", asmdict[float64, float64]) def _test_inspect_sass(self, kernel, name, sass): # Ensure function appears in output seen_function = False for line in sass.split(): if '.text' in line and name in line: seen_function = True self.assertTrue(seen_function) self.assertRegex(sass, r'//## File ".*/test_inspect.py", line [0-9]') # Some instructions common to all supported architectures that should # appear in the output self.assertIn('S2R', sass) # Special register to register self.assertIn('BRA', sass) # Branch self.assertIn('EXIT', sass) # Exit program @skip_without_nvdisasm('nvdisasm needed for inspect_sass()') def test_inspect_sass_eager(self): sig = (float32[::1], int32[::1]) @cuda.jit(sig, lineinfo=True) def add(x, y): i = cuda.grid(1) if i < len(x): x[i] += y[i] self._test_inspect_sass(add, 'add', add.inspect_sass(sig)) @skip_without_nvdisasm('nvdisasm needed for inspect_sass()') def test_inspect_sass_lazy(self): @cuda.jit(lineinfo=True) def add(x, y): i = cuda.grid(1) if i < len(x): x[i] += y[i] x = np.arange(10).astype(np.int32) y = np.arange(10).astype(np.float32) add[1, 10](x, y) signature = (int32[::1], float32[::1]) self._test_inspect_sass(add, 'add', add.inspect_sass(signature)) @skip_with_nvdisasm('Missing nvdisasm exception only generated when it is ' 'not present') def test_inspect_sass_nvdisasm_missing(self): @cuda.jit((float32[::1],)) def f(x): x[0] = 0 with self.assertRaises(RuntimeError) as raises: f.inspect_sass() self.assertIn('nvdisasm has not been found', str(raises.exception)) @skip_without_nvdisasm('nvdisasm needed for inspect_sass_cfg()') def test_inspect_sass_cfg(self): sig = (float32[::1], int32[::1]) @cuda.jit(sig) def add(x, y): i = cuda.grid(1) if i < len(x): x[i] += y[i] self.assertRegex( add.inspect_sass_cfg(signature=sig), r'digraph\s*\w\s*{(.|\n)*\n}' ) if __name__ == '__main__': unittest.main()
TestInspect
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/operators/test_eks.py
{ "start": 2763, "end": 2911 }
class ____(TypedDict): fargate_profile_name: str fargate_pod_execution_role_arn: str fargate_selectors: list[Any]
BaseFargateProfileParams
python
pytorch__pytorch
torch/distributed/elastic/rendezvous/c10d_rendezvous_backend.py
{ "start": 888, "end": 10738 }
class ____(RendezvousBackend): """Represents a C10d-backed rendezvous backend. Args: store: The :py:class:`torch.distributed.Store` instance to use to communicate with the C10d store. run_id: The run id of the rendezvous. """ # See the explanation in the __init__ method. _NULL_SENTINEL = "Y2FuaW1hZGFt" _store: Store _key: str def __init__(self, store: Store, run_id: str) -> None: if not run_id: raise ValueError("The run id must be a non-empty string.") self._store = store self._key = "torch.rendezvous." + run_id # The read operation of a store blocks the caller until the specified # key becomes available. This behavior makes it tricky to use a store # as a regular key-value dictionary. # # As a workaround we initially set a sentinel value as the rendezvous # state. Whenever this value gets returned we treat it as a None. self._call_store("compare_set", self._key, "", self._NULL_SENTINEL) @property def name(self) -> str: """See base class.""" return "c10d" def get_state(self) -> tuple[bytes, Token] | None: """See base class.""" base64_state: bytes = self._call_store("get", self._key) return self._decode_state(base64_state) def set_state( self, state: bytes, token: Token | None = None ) -> tuple[bytes, Token, bool] | None: """See base class.""" base64_state_str: str = b64encode(state).decode() if token: # Shortcut if we know for sure that the token is not valid. if not isinstance(token, bytes): result = self.get_state() if result is not None: return *result, False return None token = token.decode() else: token = self._NULL_SENTINEL base64_state: bytes = self._call_store( "compare_set", self._key, token, base64_state_str ) state_token_pair = self._decode_state(base64_state) if state_token_pair is None: return None new_state, new_token = state_token_pair # C10d Store's compare_set method does not offer an easy way to find out # whether our write attempt was successful. As a brute-force solution we # perform a bitwise comparison of our local state and the remote state. return new_state, new_token, new_state == state def _call_store(self, store_op: str, *args, **kwargs) -> Any: try: return getattr(self._store, store_op)(*args, **kwargs) except (ValueError, RuntimeError, TimeoutError) as exc: raise RendezvousConnectionError( "The connection to the C10d store has failed. See inner exception for details." ) from exc def _decode_state(self, base64_state: bytes) -> tuple[bytes, Token] | None: if base64_state == self._NULL_SENTINEL.encode(): return None try: state = b64decode(base64_state) except binascii.Error as exc: raise RendezvousStateError( "The state object is corrupt. See inner exception for details." ) from exc return state, base64_state def _create_tcp_store(params: RendezvousParameters) -> TCPStore: host, port = parse_rendezvous_endpoint(params.endpoint, default_port=DEFAULT_PORT) cfg_is_host = params.get_as_bool("is_host") # If the user has explicitly specified whether our process should host the # the store, respect it. if cfg_is_host is not None: is_host = cfg_is_host # Otherwise try to determine whether we are the host based on our hostname # and IP address. else: is_host = _matches_machine_hostname(host) # The timeout read_timeout = cast(int, params.get_as_int("read_timeout", 60)) if read_timeout <= 0: raise ValueError("The read timeout must be a positive integer.") # In specific cases we attempt to instantiate the store twice. For details # see the explanation in the except clause below. for is_server in [is_host, False]: try: store = TCPStore( host, port, is_master=is_server, multi_tenant=True, timeout=timedelta(seconds=read_timeout), ) if is_server: msg = f"Process {os.getpid()} hosts the TCP store for the C10d rendezvous backend." construct_and_record_rdzv_event( run_id=params.run_id, message=msg, node_state=NodeState.INIT ) logger.info(msg) break except (ValueError, RuntimeError, TimeoutError) as exc: # If we heuristically inferred the value of is_host as True and our # first attempt to instantiate the TCP store has failed, try it one # more time with is_host set to False. As an edge case there can be # more than one process that is part of the same rendezvous on this # machine and only one of them will eventually host the store. if not is_server or cfg_is_host is not None: raise RendezvousConnectionError( "The connection to the C10d store has failed. See inner exception for details." ) from exc return store # type: ignore[possibly-undefined] def _create_file_store(params: RendezvousParameters) -> FileStore: # If a user specifies an endpoint, we treat it as a path to a file. if params.endpoint: path = params.endpoint else: try: # The temporary file is readable and writable only by the user of # this process. _, path = tempfile.mkstemp() except OSError as exc: raise RendezvousError( "The file creation for C10d store has failed. See inner exception for details." ) from exc try: store = FileStore(path) except (ValueError, RuntimeError) as exc: raise RendezvousConnectionError( "The connection to the C10d store has failed. See inner exception for details." ) from exc return store def create_backend(params: RendezvousParameters) -> tuple[C10dRendezvousBackend, Store]: """Create a new :py:class:`C10dRendezvousBackend` from the specified parameters. +--------------+-----------------------------------------------------------+ | Parameter | Description | +==============+===========================================================+ | store_type | The type of the C10d store. The currently supported types | | | are "tcp" and "file" which correspond to | | | :py:class:`torch.distributed.TCPStore` and | | | :py:class:`torch.distributed.FileStore`, respectively. | | | Defaults to "tcp". | +--------------+-----------------------------------------------------------+ | read_timeout | The read timeout, in seconds, for store operations. | | | Defaults to 60 seconds. | | | | | | Note this only applies to | | | :py:class:`torch.distributed.TCPStore`. It is not relevant| | | to :py:class:`torch.distributed.FileStore` which does not | | | take in timeout as a parameter. | +--------------+-----------------------------------------------------------+ | is_host | A boolean value indicating whether this backend instance | | | will host the C10d store. If not specified it will be | | | inferred heuristically by matching the hostname or the IP | | | address of this machine against the specified rendezvous | | | endpoint. Defaults to ``None``. | | | | | | Note that this configuration option only applies to | | | :py:class:`torch.distributed.TCPStore`. In normal | | | circumstances you can safely skip it; the only time when | | | it is needed is if its value cannot be correctly | | | determined (e.g. the rendezvous endpoint has a CNAME as | | | the hostname or does not match the FQDN of the machine). | +--------------+-----------------------------------------------------------+ """ # As of today we only support TCPStore and FileStore. Other store types do # not have the required functionality (e.g. compare_set) yet. store_type = params.get("store_type", "tcp").strip().lower() store: Store try: if store_type == "file": store = _create_file_store(params) elif store_type == "tcp": store = _create_tcp_store(params) else: raise ValueError( "Invalid store type given. Currently only supports file and tcp." ) backend = C10dRendezvousBackend(store, params.run_id) except Exception as e: construct_and_record_rdzv_event( message=f"{type(e).__name__}: {str(e)}", run_id=params.run_id, node_state=NodeState.FAILED, ) raise return backend, store
C10dRendezvousBackend
python
django__django
tests/model_fields/test_durationfield.py
{ "start": 236, "end": 899 }
class ____(TestCase): def test_simple_roundtrip(self): duration = datetime.timedelta(microseconds=8999999999999999) DurationModel.objects.create(field=duration) loaded = DurationModel.objects.get() self.assertEqual(loaded.field, duration) def test_create_empty(self): NullDurationModel.objects.create() loaded = NullDurationModel.objects.get() self.assertIsNone(loaded.field) def test_fractional_seconds(self): value = datetime.timedelta(seconds=2.05) d = DurationModel.objects.create(field=value) d.refresh_from_db() self.assertEqual(d.field, value)
TestSaveLoad
python
sqlalchemy__sqlalchemy
test/ext/test_mutable.py
{ "start": 26116, "end": 26601 }
class ____( _MutableNoHashFixture, _MutableListTestBase, fixtures.MappedTest ): @classmethod def define_tables(cls, metadata): MutableList = cls._type_fixture() mutable_pickle = MutableList.as_mutable(PickleType) Table( "foo", metadata, Column( "id", Integer, primary_key=True, test_needs_autoincrement=True ), Column("data", mutable_pickle), )
MutableListNoHashTest
python
Unity-Technologies__ml-agents
ml-agents/mlagents/trainers/environment_parameter_manager.py
{ "start": 359, "end": 8458 }
class ____: def __init__( self, settings: Optional[Dict[str, EnvironmentParameterSettings]] = None, run_seed: int = -1, restore: bool = False, ): """ EnvironmentParameterManager manages all the environment parameters of a training session. It determines when parameters should change and gives access to the current sampler of each parameter. :param settings: A dictionary from environment parameter to EnvironmentParameterSettings. :param run_seed: When the seed is not provided for an environment parameter, this seed will be used instead. :param restore: If true, the EnvironmentParameterManager will use the GlobalTrainingStatus to try and reload the lesson status of each environment parameter. """ if settings is None: settings = {} self._dict_settings = settings for parameter_name in self._dict_settings.keys(): initial_lesson = GlobalTrainingStatus.get_parameter_state( parameter_name, StatusType.LESSON_NUM ) if initial_lesson is None or not restore: GlobalTrainingStatus.set_parameter_state( parameter_name, StatusType.LESSON_NUM, 0 ) self._smoothed_values: Dict[str, float] = defaultdict(float) for key in self._dict_settings.keys(): self._smoothed_values[key] = 0.0 # Update the seeds of the samplers self._set_sampler_seeds(run_seed) def _set_sampler_seeds(self, seed): """ Sets the seeds for the samplers (if no seed was already present). Note that using the provided seed. """ offset = 0 for settings in self._dict_settings.values(): for lesson in settings.curriculum: if lesson.value.seed == -1: lesson.value.seed = seed + offset offset += 1 def get_minimum_reward_buffer_size(self, behavior_name: str) -> int: """ Calculates the minimum size of the reward buffer a behavior must use. This method uses the 'min_lesson_length' sampler_parameter to determine this value. :param behavior_name: The name of the behavior the minimum reward buffer size corresponds to. """ result = 1 for settings in self._dict_settings.values(): for lesson in settings.curriculum: if lesson.completion_criteria is not None: if lesson.completion_criteria.behavior == behavior_name: result = max( result, lesson.completion_criteria.min_lesson_length ) return result def get_current_samplers(self) -> Dict[str, ParameterRandomizationSettings]: """ Creates a dictionary from environment parameter name to their corresponding ParameterRandomizationSettings. If curriculum is used, the ParameterRandomizationSettings corresponds to the sampler of the current lesson. """ samplers: Dict[str, ParameterRandomizationSettings] = {} for param_name, settings in self._dict_settings.items(): lesson_num = GlobalTrainingStatus.get_parameter_state( param_name, StatusType.LESSON_NUM ) lesson = settings.curriculum[lesson_num] samplers[param_name] = lesson.value return samplers def get_current_lesson_number(self) -> Dict[str, int]: """ Creates a dictionary from environment parameter to the current lesson number. If not using curriculum, this number is always 0 for that environment parameter. """ result: Dict[str, int] = {} for parameter_name in self._dict_settings.keys(): result[parameter_name] = GlobalTrainingStatus.get_parameter_state( parameter_name, StatusType.LESSON_NUM ) return result def log_current_lesson(self, parameter_name: Optional[str] = None) -> None: """ Logs the current lesson number and sampler value of the parameter with name parameter_name. If no parameter_name is provided, the values and lesson numbers of all parameters will be displayed. """ if parameter_name is not None: settings = self._dict_settings[parameter_name] lesson_number = GlobalTrainingStatus.get_parameter_state( parameter_name, StatusType.LESSON_NUM ) lesson_name = settings.curriculum[lesson_number].name lesson_value = settings.curriculum[lesson_number].value logger.info( f"Parameter '{parameter_name}' is in lesson '{lesson_name}' " f"and has value '{lesson_value}'." ) else: for parameter_name, settings in self._dict_settings.items(): lesson_number = GlobalTrainingStatus.get_parameter_state( parameter_name, StatusType.LESSON_NUM ) lesson_name = settings.curriculum[lesson_number].name lesson_value = settings.curriculum[lesson_number].value logger.info( f"Parameter '{parameter_name}' is in lesson '{lesson_name}' " f"and has value '{lesson_value}'." ) def update_lessons( self, trainer_steps: Dict[str, int], trainer_max_steps: Dict[str, int], trainer_reward_buffer: Dict[str, List[float]], ) -> Tuple[bool, bool]: """ Given progress metrics, calculates if at least one environment parameter is in a new lesson and if at least one environment parameter requires the env to reset. :param trainer_steps: A dictionary from behavior_name to the number of training steps this behavior's trainer has performed. :param trainer_max_steps: A dictionary from behavior_name to the maximum number of training steps this behavior's trainer has performed. :param trainer_reward_buffer: A dictionary from behavior_name to the list of the most recent episode returns for this behavior's trainer. :returns: A tuple of two booleans : (True if any lesson has changed, True if environment needs to reset) """ must_reset = False updated = False for param_name, settings in self._dict_settings.items(): lesson_num = GlobalTrainingStatus.get_parameter_state( param_name, StatusType.LESSON_NUM ) next_lesson_num = lesson_num + 1 lesson = settings.curriculum[lesson_num] if ( lesson.completion_criteria is not None and len(settings.curriculum) > next_lesson_num ): behavior_to_consider = lesson.completion_criteria.behavior if behavior_to_consider in trainer_steps: ( must_increment, new_smoothing, ) = lesson.completion_criteria.need_increment( float(trainer_steps[behavior_to_consider]) / float(trainer_max_steps[behavior_to_consider]), trainer_reward_buffer[behavior_to_consider], self._smoothed_values[param_name], ) self._smoothed_values[param_name] = new_smoothing if must_increment: GlobalTrainingStatus.set_parameter_state( param_name, StatusType.LESSON_NUM, next_lesson_num ) self.log_current_lesson(param_name) updated = True if lesson.completion_criteria.require_reset: must_reset = True return updated, must_reset
EnvironmentParameterManager
python
tiangolo__fastapi
tests/test_jsonable_encoder.py
{ "start": 1438, "end": 9326 }
class ____(BaseModel): foo: str = ... # type: ignore bar: str = "bar" bla: str = "bla" def test_encode_dict(): pet = {"name": "Firulais", "owner": {"name": "Foo"}} assert jsonable_encoder(pet) == {"name": "Firulais", "owner": {"name": "Foo"}} assert jsonable_encoder(pet, include={"name"}) == {"name": "Firulais"} assert jsonable_encoder(pet, exclude={"owner"}) == {"name": "Firulais"} assert jsonable_encoder(pet, include={}) == {} assert jsonable_encoder(pet, exclude={}) == { "name": "Firulais", "owner": {"name": "Foo"}, } def test_encode_class(): person = Person(name="Foo") pet = Pet(owner=person, name="Firulais") assert jsonable_encoder(pet) == {"name": "Firulais", "owner": {"name": "Foo"}} assert jsonable_encoder(pet, include={"name"}) == {"name": "Firulais"} assert jsonable_encoder(pet, exclude={"owner"}) == {"name": "Firulais"} assert jsonable_encoder(pet, include={}) == {} assert jsonable_encoder(pet, exclude={}) == { "name": "Firulais", "owner": {"name": "Foo"}, } def test_encode_dictable(): person = DictablePerson(name="Foo") pet = DictablePet(owner=person, name="Firulais") assert jsonable_encoder(pet) == {"name": "Firulais", "owner": {"name": "Foo"}} assert jsonable_encoder(pet, include={"name"}) == {"name": "Firulais"} assert jsonable_encoder(pet, exclude={"owner"}) == {"name": "Firulais"} assert jsonable_encoder(pet, include={}) == {} assert jsonable_encoder(pet, exclude={}) == { "name": "Firulais", "owner": {"name": "Foo"}, } def test_encode_dataclass(): item = Item(name="foo", count=100) assert jsonable_encoder(item) == {"name": "foo", "count": 100} assert jsonable_encoder(item, include={"name"}) == {"name": "foo"} assert jsonable_encoder(item, exclude={"count"}) == {"name": "foo"} assert jsonable_encoder(item, include={}) == {} assert jsonable_encoder(item, exclude={}) == {"name": "foo", "count": 100} def test_encode_unsupported(): unserializable = Unserializable() with pytest.raises(ValueError): jsonable_encoder(unserializable) @needs_pydanticv2 def test_encode_custom_json_encoders_model_pydanticv2(): from pydantic import field_serializer class ModelWithCustomEncoder(BaseModel): dt_field: datetime @field_serializer("dt_field") def serialize_dt_field(self, dt): return dt.replace(microsecond=0, tzinfo=timezone.utc).isoformat() class ModelWithCustomEncoderSubclass(ModelWithCustomEncoder): pass model = ModelWithCustomEncoder(dt_field=datetime(2019, 1, 1, 8)) assert jsonable_encoder(model) == {"dt_field": "2019-01-01T08:00:00+00:00"} subclass_model = ModelWithCustomEncoderSubclass(dt_field=datetime(2019, 1, 1, 8)) assert jsonable_encoder(subclass_model) == {"dt_field": "2019-01-01T08:00:00+00:00"} # TODO: remove when deprecating Pydantic v1 @needs_pydanticv1 def test_encode_custom_json_encoders_model_pydanticv1(): class ModelWithCustomEncoder(BaseModel): dt_field: datetime class Config: json_encoders = { datetime: lambda dt: dt.replace( microsecond=0, tzinfo=timezone.utc ).isoformat() } class ModelWithCustomEncoderSubclass(ModelWithCustomEncoder): class Config: pass model = ModelWithCustomEncoder(dt_field=datetime(2019, 1, 1, 8)) assert jsonable_encoder(model) == {"dt_field": "2019-01-01T08:00:00+00:00"} subclass_model = ModelWithCustomEncoderSubclass(dt_field=datetime(2019, 1, 1, 8)) assert jsonable_encoder(subclass_model) == {"dt_field": "2019-01-01T08:00:00+00:00"} def test_encode_model_with_config(): model = ModelWithConfig(role=RoleEnum.admin) assert jsonable_encoder(model) == {"role": "admin"} def test_encode_model_with_alias_raises(): with pytest.raises(ValidationError): ModelWithAlias(foo="Bar") def test_encode_model_with_alias(): model = ModelWithAlias(Foo="Bar") assert jsonable_encoder(model) == {"Foo": "Bar"} def test_encode_model_with_default(): model = ModelWithDefault(foo="foo", bar="bar") assert jsonable_encoder(model) == {"foo": "foo", "bar": "bar", "bla": "bla"} assert jsonable_encoder(model, exclude_unset=True) == {"foo": "foo", "bar": "bar"} assert jsonable_encoder(model, exclude_defaults=True) == {"foo": "foo"} assert jsonable_encoder(model, exclude_unset=True, exclude_defaults=True) == { "foo": "foo" } assert jsonable_encoder(model, include={"foo"}) == {"foo": "foo"} assert jsonable_encoder(model, exclude={"bla"}) == {"foo": "foo", "bar": "bar"} assert jsonable_encoder(model, include={}) == {} assert jsonable_encoder(model, exclude={}) == { "foo": "foo", "bar": "bar", "bla": "bla", } @needs_pydanticv1 def test_custom_encoders(): class safe_datetime(datetime): pass class MyModel(BaseModel): dt_field: safe_datetime instance = MyModel(dt_field=safe_datetime.now()) encoded_instance = jsonable_encoder( instance, custom_encoder={safe_datetime: lambda o: o.strftime("%H:%M:%S")} ) assert encoded_instance["dt_field"] == instance.dt_field.strftime("%H:%M:%S") encoded_instance2 = jsonable_encoder(instance) assert encoded_instance2["dt_field"] == instance.dt_field.isoformat() def test_custom_enum_encoders(): def custom_enum_encoder(v: Enum): return v.value.lower() class MyEnum(Enum): ENUM_VAL_1 = "ENUM_VAL_1" instance = MyEnum.ENUM_VAL_1 encoded_instance = jsonable_encoder( instance, custom_encoder={MyEnum: custom_enum_encoder} ) assert encoded_instance == custom_enum_encoder(instance) def test_encode_model_with_pure_path(): class ModelWithPath(BaseModel): path: PurePath if PYDANTIC_V2: model_config = {"arbitrary_types_allowed": True} else: class Config: arbitrary_types_allowed = True test_path = PurePath("/foo", "bar") obj = ModelWithPath(path=test_path) assert jsonable_encoder(obj) == {"path": str(test_path)} def test_encode_model_with_pure_posix_path(): class ModelWithPath(BaseModel): path: PurePosixPath if PYDANTIC_V2: model_config = {"arbitrary_types_allowed": True} else: class Config: arbitrary_types_allowed = True obj = ModelWithPath(path=PurePosixPath("/foo", "bar")) assert jsonable_encoder(obj) == {"path": "/foo/bar"} def test_encode_model_with_pure_windows_path(): class ModelWithPath(BaseModel): path: PureWindowsPath if PYDANTIC_V2: model_config = {"arbitrary_types_allowed": True} else: class Config: arbitrary_types_allowed = True obj = ModelWithPath(path=PureWindowsPath("/foo", "bar")) assert jsonable_encoder(obj) == {"path": "\\foo\\bar"} @needs_pydanticv1 def test_encode_root(): class ModelWithRoot(BaseModel): __root__: str model = ModelWithRoot(__root__="Foo") assert jsonable_encoder(model) == "Foo" @needs_pydanticv2 def test_decimal_encoder_float(): data = {"value": Decimal(1.23)} assert jsonable_encoder(data) == {"value": 1.23} @needs_pydanticv2 def test_decimal_encoder_int(): data = {"value": Decimal(2)} assert jsonable_encoder(data) == {"value": 2} def test_encode_deque_encodes_child_models(): class Model(BaseModel): test: str dq = deque([Model(test="test")]) assert jsonable_encoder(dq)[0]["test"] == "test" @needs_pydanticv2 def test_encode_pydantic_undefined(): data = {"value": Undefined} assert jsonable_encoder(data) == {"value": None}
ModelWithDefault
python
PrefectHQ__prefect
tests/server/models/test_block_types.py
{ "start": 8885, "end": 10245 }
class ____: async def test_update_block_type(self, session, block_type_x): assert await models.block_types.update_block_type( session, block_type_id=block_type_x.id, block_type=schemas.actions.BlockTypeUpdate( logo_url="http://example.com/logo.png", documentation_url="http://example.com/documentation.html", description="A block, verily", code_example=CODE_EXAMPLE, ), ) db_block_type = await models.block_types.read_block_type( session=session, block_type_id=block_type_x.id ) assert db_block_type.logo_url == "http://example.com/logo.png" assert ( db_block_type.documentation_url == "http://example.com/documentation.html" ) assert db_block_type.description == "A block, verily" assert db_block_type.code_example == CODE_EXAMPLE async def test_update_nonexistant_block_type(self, session): assert not await models.block_types.update_block_type( session, block_type_id=uuid4(), block_type=schemas.actions.BlockTypeUpdate( logo_url="http://example.com/logo.png", documentation_url="http://example.com/documentation.html", ), )
TestUpdateBlockType
python
scipy__scipy
scipy/integrate/tests/test__quad_vec.py
{ "start": 451, "end": 7157 }
class ____: @quadrature_params def test_quad_vec_simple(self, quadrature): n = np.arange(10) def f(x): return x ** n for epsabs in [0.1, 1e-3, 1e-6]: if quadrature == 'trapezoid' and epsabs < 1e-4: # slow: skip continue kwargs = dict(epsabs=epsabs, quadrature=quadrature) exact = 2**(n+1)/(n + 1) res, err = quad_vec(f, 0, 2, norm='max', **kwargs) assert_allclose(res, exact, rtol=0, atol=epsabs) res, err = quad_vec(f, 0, 2, norm='2', **kwargs) assert np.linalg.norm(res - exact) < epsabs res, err = quad_vec(f, 0, 2, norm='max', points=(0.5, 1.0), **kwargs) assert_allclose(res, exact, rtol=0, atol=epsabs) res, err, *rest = quad_vec(f, 0, 2, norm='max', epsrel=1e-8, full_output=True, limit=10000, **kwargs) assert_allclose(res, exact, rtol=0, atol=epsabs) @quadrature_params def test_quad_vec_simple_inf(self, quadrature): def f(x): return 1 / (1 + np.float64(x) ** 2) for epsabs in [0.1, 1e-3, 1e-6]: if quadrature == 'trapezoid' and epsabs < 1e-4: # slow: skip continue kwargs = dict(norm='max', epsabs=epsabs, quadrature=quadrature) res, err = quad_vec(f, 0, np.inf, **kwargs) assert_allclose(res, np.pi/2, rtol=0, atol=max(epsabs, err)) res, err = quad_vec(f, 0, -np.inf, **kwargs) assert_allclose(res, -np.pi/2, rtol=0, atol=max(epsabs, err)) res, err = quad_vec(f, -np.inf, 0, **kwargs) assert_allclose(res, np.pi/2, rtol=0, atol=max(epsabs, err)) res, err = quad_vec(f, np.inf, 0, **kwargs) assert_allclose(res, -np.pi/2, rtol=0, atol=max(epsabs, err)) res, err = quad_vec(f, -np.inf, np.inf, **kwargs) assert_allclose(res, np.pi, rtol=0, atol=max(epsabs, err)) res, err = quad_vec(f, np.inf, -np.inf, **kwargs) assert_allclose(res, -np.pi, rtol=0, atol=max(epsabs, err)) res, err = quad_vec(f, np.inf, np.inf, **kwargs) assert_allclose(res, 0, rtol=0, atol=max(epsabs, err)) res, err = quad_vec(f, -np.inf, -np.inf, **kwargs) assert_allclose(res, 0, rtol=0, atol=max(epsabs, err)) res, err = quad_vec(f, 0, np.inf, points=(1.0, 2.0), **kwargs) assert_allclose(res, np.pi/2, rtol=0, atol=max(epsabs, err)) def f(x): return np.sin(x + 2) / (1 + x ** 2) exact = np.pi / np.e * np.sin(2) epsabs = 1e-5 res, err, info = quad_vec(f, -np.inf, np.inf, limit=1000, norm='max', epsabs=epsabs, quadrature=quadrature, full_output=True) assert info.status == 1 assert_allclose(res, exact, rtol=0, atol=max(epsabs, 1.5 * err)) def test_quad_vec_args(self): def f(x, a): return x * (x + a) * np.arange(3) a = 2 exact = np.array([0, 4/3, 8/3]) res, err = quad_vec(f, 0, 1, args=(a,)) assert_allclose(res, exact, rtol=0, atol=1e-4) @pytest.mark.fail_slow(10) def test_quad_vec_pool(self): f = _lorenzian res, err = quad_vec(f, -np.inf, np.inf, norm='max', epsabs=1e-4, workers=4) assert_allclose(res, np.pi, rtol=0, atol=1e-4) with Pool(10) as pool: def f(x): return 1 / (1 + x ** 2) res, _ = quad_vec(f, -np.inf, np.inf, norm='max', epsabs=1e-4, workers=pool.map) assert_allclose(res, np.pi, rtol=0, atol=1e-4) @pytest.mark.fail_slow(10) @pytest.mark.parametrize('extra_args', [2, (2,)]) @pytest.mark.parametrize( 'workers', [1, pytest.param(10, marks=pytest.mark.parallel_threads_limit(4))] ) def test_quad_vec_pool_args(self, extra_args, workers): f = _func_with_args exact = np.array([0, 4/3, 8/3]) res, err = quad_vec(f, 0, 1, args=extra_args, workers=workers) assert_allclose(res, exact, rtol=0, atol=1e-4) with Pool(workers) as pool: res, err = quad_vec(f, 0, 1, args=extra_args, workers=pool.map) assert_allclose(res, exact, rtol=0, atol=1e-4) @quadrature_params def test_num_eval(self, quadrature): def f(x): count[0] += 1 return x**5 count = [0] res = quad_vec(f, 0, 1, norm='max', full_output=True, quadrature=quadrature) assert res[2].neval == count[0] def test_info(self): def f(x): return np.ones((3, 2, 1)) res, err, info = quad_vec(f, 0, 1, norm='max', full_output=True) assert info.success is True assert info.status == 0 assert info.message == 'Target precision reached.' assert info.neval > 0 assert info.intervals.shape[1] == 2 assert info.integrals.shape == (info.intervals.shape[0], 3, 2, 1) assert info.errors.shape == (info.intervals.shape[0],) def test_nan_inf(self): def f_nan(x): return np.nan def f_inf(x): return np.inf if x < 0.1 else 1/x res, err, info = quad_vec(f_nan, 0, 1, full_output=True) assert info.status == 3 res, err, info = quad_vec(f_inf, 0, 1, full_output=True) assert info.status == 3 @pytest.mark.parametrize('a,b', [(0, 1), (0, np.inf), (np.inf, 0), (-np.inf, np.inf), (np.inf, -np.inf)]) def test_points(self, a, b): # Check that initial interval splitting is done according to # `points`, by checking that consecutive sets of 15 point (for # gk15) function evaluations lie between `points` points = (0, 0.25, 0.5, 0.75, 1.0) points += tuple(-x for x in points) quadrature_points = 15 interval_sets = [] count = 0 def f(x): nonlocal count if count % quadrature_points == 0: interval_sets.append(set()) count += 1 interval_sets[-1].add(float(x)) return 0.0 quad_vec(f, a, b, points=points, quadrature='gk15', limit=0) # Check that all point sets lie in a single `points` interval for p in interval_sets: j = np.searchsorted(sorted(points), tuple(p)) assert np.all(j == j[0])
TestQuadVec
python
numba__numba
numba/core/typing/npdatetime.py
{ "start": 8291, "end": 8377 }
class ____(DatetimeCmpOp): key = operator.gt @infer_global(operator.ge)
DatetimeCmpGt
python
tensorflow__tensorflow
tensorflow/python/framework/errors_impl.py
{ "start": 17454, "end": 19883 }
class ____(OpError): """Raised when unrecoverable data loss or corruption is encountered. This could be due to: * A truncated file. * A corrupted file. * Specifying the wrong data format. For example, this may be raised by running a `tf.WholeFileReader.read` operation, if the file is truncated while it is being read. """ def __init__(self, node_def, op, message, *args): """Creates a `DataLossError`.""" super(DataLossError, self).__init__(node_def, op, message, DATA_LOSS, *args) _CODE_TO_EXCEPTION_CLASS = { CANCELLED: CancelledError, UNKNOWN: UnknownError, INVALID_ARGUMENT: InvalidArgumentError, DEADLINE_EXCEEDED: DeadlineExceededError, NOT_FOUND: NotFoundError, ALREADY_EXISTS: AlreadyExistsError, PERMISSION_DENIED: PermissionDeniedError, UNAUTHENTICATED: UnauthenticatedError, RESOURCE_EXHAUSTED: ResourceExhaustedError, FAILED_PRECONDITION: FailedPreconditionError, ABORTED: AbortedError, OUT_OF_RANGE: OutOfRangeError, UNIMPLEMENTED: UnimplementedError, INTERNAL: InternalError, UNAVAILABLE: UnavailableError, DATA_LOSS: DataLossError, } _pywrap_py_exception_registry.PyExceptionRegistry_Init(_CODE_TO_EXCEPTION_CLASS) _EXCEPTION_CLASS_TO_CODE = { class_: code for code, class_ in _CODE_TO_EXCEPTION_CLASS.items() } @tf_export(v1=["errors.exception_type_from_error_code"]) def exception_type_from_error_code(error_code): return _CODE_TO_EXCEPTION_CLASS[error_code] @tf_export(v1=["errors.error_code_from_exception_type"]) def error_code_from_exception_type(cls): try: return _EXCEPTION_CLASS_TO_CODE[cls] except KeyError: warnings.warn("Unknown class exception") return UnknownError(None, None, "Unknown class exception", None) def _make_specific_exception(node_def, op, message, error_code): try: exc_type = exception_type_from_error_code(error_code) return exc_type(node_def, op, message) except KeyError: warnings.warn("Unknown error code: %d" % error_code) return UnknownError(node_def, op, message, error_code) # Named like a function for backwards compatibility with the # @tf_contextlib.contextmanager version, which was switched to a class to avoid # some object creation overhead. # TODO(b/77295559): expand use of TF_Status* SWIG typemap and deprecate this. @tf_export(v1=["errors.raise_exception_on_not_ok_status"]) # pylint: disable=invalid-name
DataLossError
python
eriklindernoren__ML-From-Scratch
mlfromscratch/unsupervised_learning/restricted_boltzmann_machine.py
{ "start": 241, "end": 3357 }
class ____(): """Bernoulli Restricted Boltzmann Machine (RBM) Parameters: ----------- n_hidden: int: The number of processing nodes (neurons) in the hidden layer. learning_rate: float The step length that will be used when updating the weights. batch_size: int The size of the mini-batch used to calculate each weight update. n_iterations: float The number of training iterations the algorithm will tune the weights for. Reference: A Practical Guide to Training Restricted Boltzmann Machines URL: https://www.cs.toronto.edu/~hinton/absps/guideTR.pdf """ def __init__(self, n_hidden=128, learning_rate=0.1, batch_size=10, n_iterations=100): self.n_iterations = n_iterations self.batch_size = batch_size self.lr = learning_rate self.n_hidden = n_hidden self.progressbar = progressbar.ProgressBar(widgets=bar_widgets) def _initialize_weights(self, X): n_visible = X.shape[1] self.W = np.random.normal(scale=0.1, size=(n_visible, self.n_hidden)) self.v0 = np.zeros(n_visible) # Bias visible self.h0 = np.zeros(self.n_hidden) # Bias hidden def fit(self, X, y=None): '''Contrastive Divergence training procedure''' self._initialize_weights(X) self.training_errors = [] self.training_reconstructions = [] for _ in self.progressbar(range(self.n_iterations)): batch_errors = [] for batch in batch_iterator(X, batch_size=self.batch_size): # Positive phase positive_hidden = sigmoid(batch.dot(self.W) + self.h0) hidden_states = self._sample(positive_hidden) positive_associations = batch.T.dot(positive_hidden) # Negative phase negative_visible = sigmoid(hidden_states.dot(self.W.T) + self.v0) negative_visible = self._sample(negative_visible) negative_hidden = sigmoid(negative_visible.dot(self.W) + self.h0) negative_associations = negative_visible.T.dot(negative_hidden) self.W += self.lr * (positive_associations - negative_associations) self.h0 += self.lr * (positive_hidden.sum(axis=0) - negative_hidden.sum(axis=0)) self.v0 += self.lr * (batch.sum(axis=0) - negative_visible.sum(axis=0)) batch_errors.append(np.mean((batch - negative_visible) ** 2)) self.training_errors.append(np.mean(batch_errors)) # Reconstruct a batch of images from the training set idx = np.random.choice(range(X.shape[0]), self.batch_size) self.training_reconstructions.append(self.reconstruct(X[idx])) def _sample(self, X): return X > np.random.random_sample(size=X.shape) def reconstruct(self, X): positive_hidden = sigmoid(X.dot(self.W) + self.h0) hidden_states = self._sample(positive_hidden) negative_visible = sigmoid(hidden_states.dot(self.W.T) + self.v0) return negative_visible
RBM
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typedDict9.py
{ "start": 197, "end": 455 }
class ____(TypedDict): outer_key: Inner2 o1: Outer1 = {"outer_key": {"inner_key": {"inner_key": "hi"}}} # This should generate an error because the inner-most value # should be a string. o2: Outer1 = {"outer_key": {"inner_key": {"inner_key": 1}}}
Outer1
python
spyder-ide__spyder
spyder/plugins/editor/widgets/editorstack/helpers.py
{ "start": 974, "end": 4291 }
class ____(QObject): """Analysis thread manager.""" def __init__(self, parent, max_simultaneous_threads=2): """Initialize the ThreadManager.""" super().__init__(parent) self.max_simultaneous_threads = max_simultaneous_threads self.started_threads = {} self.pending_threads = [] self.end_callbacks = {} def close_threads(self, parent): """Close threads associated to parent_id.""" logger.debug("Call ThreadManager's 'close_threads'") if parent is None: # Closing all threads self.pending_threads = [] threadlist = [] for threads in list(self.started_threads.values()): threadlist += threads else: parent_id = id(parent) self.pending_threads = [(_th, _id) for (_th, _id) in self.pending_threads if _id != parent_id] threadlist = self.started_threads.get(parent_id, []) for thread in threadlist: logger.debug("Waiting for thread %r to finish" % thread) while thread.isRunning(): # We can't terminate thread safely, so we simply wait... QApplication.processEvents() def close_all_threads(self): """Close all threads.""" logger.debug("Call ThreadManager's 'close_all_threads'") self.close_threads(None) def add_thread(self, checker, end_callback, source_code, parent): """Add thread to queue.""" parent_id = id(parent) thread = AnalysisThread(None, checker, source_code) self.end_callbacks[id(thread)] = end_callback self.pending_threads.append((thread, parent_id)) logger.debug("Added thread %r to queue" % thread) QTimer.singleShot(50, self.update_queue) def update_queue(self): """Update queue.""" started = 0 for parent_id, threadlist in list(self.started_threads.items()): still_running = [] for thread in threadlist: if thread.isFinished(): end_callback = self.end_callbacks.pop(id(thread)) if thread.results is not None: # The thread was executed successfully end_callback(thread.results) thread.setParent(None) thread = None else: still_running.append(thread) started += 1 threadlist = None if still_running: self.started_threads[parent_id] = still_running else: self.started_threads.pop(parent_id) logger.debug("Updating queue:") logger.debug(" started: %d" % started) logger.debug(" pending: %d" % len(self.pending_threads)) if self.pending_threads and started < self.max_simultaneous_threads: thread, parent_id = self.pending_threads.pop(0) thread.finished.connect(self.update_queue) threadlist = self.started_threads.get(parent_id, []) self.started_threads[parent_id] = threadlist+[thread] logger.debug("===>starting: %r" % thread) thread.start()
ThreadManager
python
great-expectations__great_expectations
tests/core/test_config_substitutor.py
{ "start": 5134, "end": 7319 }
class ____: def __init__(self, secret_response): self.secret_response = secret_response def __call__(self): return self def access_secret_version(self, *args, **kwargs): class Response: pass response = Response() response._pb = Response() response._pb.payload = Response() response._pb.payload.data = self.secret_response return response # This test requires this import but monkeypatches external calls made to google. @pytest.mark.skipif( not google.secretmanager, reason="Could not import 'secretmanager' from google.cloud in data_context.util", ) @pytest.mark.parametrize( "input_value,secret_response,raises,expected", [ ( "secret|projects/project_id/secrets/my_secret", b"value", does_not_raise(), "value", ), ( "secret|projects/project_id/secrets/my_secret|key", b'{"key": "value"}', does_not_raise(), "value", ), ( "secret|projects/project_id/secrets/my_se%&et|key", None, pytest.raises(ValueError), None, ), ( "secret|projects/project_id/secrets/my_secret/version/A|key", None, pytest.raises(ValueError), None, ), ], ) @pytest.mark.unit def test_substitute_value_from_gcp_secret_manager( config_substitutor, input_value, secret_response, raises, expected ): with raises: with mock.patch( "great_expectations.core.config_substitutor.google.secretmanager.SecretManagerServiceClient", return_value=MockedSecretManagerServiceClient(secret_response), ): # As we're testing the secret store and not the actual substitution logic, # we deem the use of an empty config_variables_dict appropriate. assert ( config_substitutor.substitute_config_variable( template_str=input_value, config_variables_dict={} ) == expected )
MockedSecretManagerServiceClient
python
walkccc__LeetCode
solutions/135. Candy/135.py
{ "start": 0, "end": 390 }
class ____: def candy(self, ratings: list[int]) -> int: n = len(ratings) ans = 0 l = [1] * n r = [1] * n for i in range(1, n): if ratings[i] > ratings[i - 1]: l[i] = l[i - 1] + 1 for i in range(n - 2, -1, -1): if ratings[i] > ratings[i + 1]: r[i] = r[i + 1] + 1 for a, b in zip(l, r): ans += max(a, b) return ans
Solution
python
cython__cython
Cython/Compiler/Nodes.py
{ "start": 317671, "end": 319063 }
class ____(Node): # if or elif clause in an if statement # # condition ExprNode # body StatNode child_attrs = ["condition", "body"] branch_hint = None def analyse_declarations(self, env): self.body.analyse_declarations(env) def analyse_expressions(self, env): self.condition = self.condition.analyse_temp_boolean_expression(env) self.body = self.body.analyse_expressions(env) return self def generate_execution_code(self, code, end_label, is_last): self.condition.generate_evaluation_code(code) code.mark_pos(self.pos) condition = self.condition.result() if self.branch_hint: condition = '%s(%s)' % (self.branch_hint, condition) code.putln("if (%s) {" % condition) self.condition.generate_disposal_code(code) self.condition.free_temps(code) self.body.generate_execution_code(code) code.mark_pos(self.pos, trace=False) if not (is_last or self.body.is_terminator): code.put_goto(end_label) code.putln("}") def generate_function_definitions(self, env, code): self.condition.generate_function_definitions(env, code) self.body.generate_function_definitions(env, code) def annotate(self, code): self.condition.annotate(code) self.body.annotate(code)
IfClauseNode
python
ansible__ansible
lib/ansible/module_utils/_internal/_messages.py
{ "start": 3207, "end": 3404 }
class ____(SummaryBase): """Error summary with details (possibly derived from an exception __cause__ chain) and an optional traceback.""" @_dataclasses.dataclass(**_dataclass_kwargs)
ErrorSummary
python
pytransitions__transitions
tests/test_async.py
{ "start": 29173, "end": 33380 }
class ____(TestAsync): def setUp(self): super(TestAsync, self).setUp() self.machine_cls = HierarchicalAsyncMachine # type: Type[HierarchicalAsyncMachine] self.machine = self.machine_cls(states=['A', 'B', 'C'], transitions=[['go', 'A', 'B']], initial='A') def test_nested_async(self): mock = MagicMock() async def sleep_mock(): # type: () -> None await asyncio.sleep(0.1) mock() states = ['A', 'B', {'name': 'C', 'children': ['1', {'name': '2', 'children': ['a', 'b'], 'initial': 'a'}, '3'], 'initial': '2'}] transitions = [ {'trigger': 'go', 'source': 'A', 'dest': 'C', 'after': [sleep_mock] * 100} ] # type: Sequence[AsyncTransitionConfig] machine = self.machine_cls(states=states, transitions=transitions, initial='A') asyncio.run(machine.go()) self.assertEqual('C{0}2{0}a'.format(machine.state_cls.separator), machine.state) self.assertEqual(100, mock.call_count) def test_parallel_async(self): states = ['A', 'B', {'name': 'P', 'parallel': [ {'name': '1', 'children': ['a'], 'initial': 'a'}, {'name': '2', 'children': ['b', 'c'], 'initial': 'b'}, {'name': '3', 'children': ['x', 'y', 'z'], 'initial': 'y'}]}] machine = self.machine_cls(states=states, initial='A') asyncio.run(machine.to_P()) self.assertEqual(['P{0}1{0}a'.format(machine.state_cls.separator), 'P{0}2{0}b'.format(machine.state_cls.separator), 'P{0}3{0}y'.format(machine.state_cls.separator)], machine.state) asyncio.run(machine.to_B()) self.assertTrue(machine.is_B()) def test_final_state_nested(self): final_mock_B = MagicMock() final_mock_Y = MagicMock() final_mock_Z = MagicMock() final_mock_machine = MagicMock() mocks = [final_mock_B, final_mock_Y, final_mock_Z, final_mock_machine] states = ['A', {'name': 'B', 'parallel': [{'name': 'X', 'final': True}, {'name': 'Y', 'transitions': [['final_Y', 'yI', 'yII']], 'initial': 'yI', 'on_final': final_mock_Y, 'states': ['yI', {'name': 'yII', 'final': True}] }, {'name': 'Z', 'transitions': [['final_Z', 'zI', 'zII']], 'initial': 'zI', 'on_final': final_mock_Z, 'states': ['zI', {'name': 'zII', 'final': True}] }, ], "on_final": final_mock_B}] machine = self.machine_cls(states=states, on_final=final_mock_machine, initial='A') async def run(): self.assertFalse(any(mock.called for mock in mocks)) await machine.to_B() self.assertFalse(any(mock.called for mock in mocks)) await machine.final_Y() self.assertTrue(final_mock_Y.called) self.assertFalse(final_mock_Z.called) self.assertFalse(final_mock_B.called) self.assertFalse(final_mock_machine.called) await machine.final_Z() self.assertEqual(1, final_mock_Y.call_count) self.assertEqual(1, final_mock_Z.call_count) self.assertEqual(1, final_mock_B.call_count) self.assertEqual(1, final_mock_machine.call_count) asyncio.run(run()) @skipIf(asyncio is None or (pgv is None and gv is None), "AsyncGraphMachine requires asyncio and (py)gaphviz")
TestHierarchicalAsync
python
numpy__numpy
numpy/random/tests/test_smoke.py
{ "start": 2557, "end": 26770 }
class ____: @classmethod def _create_rng(cls): # Overridden in test classes. Place holder to silence IDE noise bit_generator = PCG64 advance = None seed = [12345] rg = Generator(bit_generator(*seed)) seed_vector_bits = 64 return RNGData(bit_generator, advance, seed, rg, seed_vector_bits) def test_init(self): data = self._create_rng() data.rg = Generator(data.bit_generator()) state = data.rg.bit_generator.state data.rg.standard_normal(1) data.rg.standard_normal(1) data.rg.bit_generator.state = state new_state = data.rg.bit_generator.state assert_(comp_state(state, new_state)) def test_advance(self): data = self._create_rng() state = data.rg.bit_generator.state if hasattr(data.rg.bit_generator, 'advance'): data.rg.bit_generator.advance(data.advance) assert_(not comp_state(state, data.rg.bit_generator.state)) else: bitgen_name = data.rg.bit_generator.__class__.__name__ pytest.skip(f'Advance is not supported by {bitgen_name}') def test_jump(self): rg = self._create_rng().rg state = rg.bit_generator.state if hasattr(rg.bit_generator, 'jumped'): bit_gen2 = rg.bit_generator.jumped() jumped_state = bit_gen2.state assert_(not comp_state(state, jumped_state)) rg.random(2 * 3 * 5 * 7 * 11 * 13 * 17) rg.bit_generator.state = state bit_gen3 = rg.bit_generator.jumped() rejumped_state = bit_gen3.state assert_(comp_state(jumped_state, rejumped_state)) else: bitgen_name = rg.bit_generator.__class__.__name__ if bitgen_name not in ('SFC64',): raise AttributeError(f'no "jumped" in {bitgen_name}') pytest.skip(f'Jump is not supported by {bitgen_name}') def test_uniform(self): rg = self._create_rng().rg r = rg.uniform(-1.0, 0.0, size=10) assert_(len(r) == 10) assert_((r > -1).all()) assert_((r <= 0).all()) def test_uniform_array(self): rg = self._create_rng().rg r = rg.uniform(np.array([-1.0] * 10), 0.0, size=10) assert_(len(r) == 10) assert_((r > -1).all()) assert_((r <= 0).all()) r = rg.uniform(np.array([-1.0] * 10), np.array([0.0] * 10), size=10) assert_(len(r) == 10) assert_((r > -1).all()) assert_((r <= 0).all()) r = rg.uniform(-1.0, np.array([0.0] * 10), size=10) assert_(len(r) == 10) assert_((r > -1).all()) assert_((r <= 0).all()) def test_random(self): rg = self._create_rng().rg assert_(len(rg.random(10)) == 10) params_0(rg.random) def test_standard_normal_zig(self): rg = self._create_rng().rg assert_(len(rg.standard_normal(10)) == 10) def test_standard_normal(self): rg = self._create_rng().rg assert_(len(rg.standard_normal(10)) == 10) params_0(rg.standard_normal) def test_standard_gamma(self): rg = self._create_rng().rg assert_(len(rg.standard_gamma(10, 10)) == 10) assert_(len(rg.standard_gamma(np.array([10] * 10), 10)) == 10) params_1(rg.standard_gamma) def test_standard_exponential(self): rg = self._create_rng().rg assert_(len(rg.standard_exponential(10)) == 10) params_0(rg.standard_exponential) def test_standard_exponential_float(self): rg = self._create_rng().rg randoms = rg.standard_exponential(10, dtype='float32') assert_(len(randoms) == 10) assert randoms.dtype == np.float32 params_0(partial(rg.standard_exponential, dtype='float32')) def test_standard_exponential_float_log(self): rg = self._create_rng().rg randoms = rg.standard_exponential(10, dtype='float32', method='inv') assert_(len(randoms) == 10) assert randoms.dtype == np.float32 params_0(partial(rg.standard_exponential, dtype='float32', method='inv')) def test_standard_cauchy(self): rg = self._create_rng().rg assert_(len(rg.standard_cauchy(10)) == 10) params_0(rg.standard_cauchy) def test_standard_t(self): rg = self._create_rng().rg assert_(len(rg.standard_t(10, 10)) == 10) params_1(rg.standard_t) def test_binomial(self): rg = self._create_rng().rg assert_(rg.binomial(10, .5) >= 0) assert_(rg.binomial(1000, .5) >= 0) def test_reset_state(self): rg = self._create_rng().rg state = rg.bit_generator.state int_1 = rg.integers(2**31) rg.bit_generator.state = state int_2 = rg.integers(2**31) assert_(int_1 == int_2) def test_entropy_init(self): bit_generator = self._create_rng().bit_generator rg = Generator(bit_generator()) rg2 = Generator(bit_generator()) assert_(not comp_state(rg.bit_generator.state, rg2.bit_generator.state)) def test_seed(self): data = self._create_rng() rg = Generator(data.bit_generator(*data.seed)) rg2 = Generator(data.bit_generator(*data.seed)) rg.random() rg2.random() assert_(comp_state(rg.bit_generator.state, rg2.bit_generator.state)) def test_reset_state_gauss(self): data = self._create_rng() rg = Generator(data.bit_generator(*data.seed)) rg.standard_normal() state = rg.bit_generator.state n1 = rg.standard_normal(size=10) rg2 = Generator(data.bit_generator()) rg2.bit_generator.state = state n2 = rg2.standard_normal(size=10) assert_array_equal(n1, n2) def test_reset_state_uint32(self): data = self._create_rng() rg = Generator(data.bit_generator(*data.seed)) rg.integers(0, 2 ** 24, 120, dtype=np.uint32) state = rg.bit_generator.state n1 = rg.integers(0, 2 ** 24, 10, dtype=np.uint32) rg2 = Generator(data.bit_generator()) rg2.bit_generator.state = state n2 = rg2.integers(0, 2 ** 24, 10, dtype=np.uint32) assert_array_equal(n1, n2) def test_reset_state_float(self): data = self._create_rng() rg = Generator(data.bit_generator(*data.seed)) rg.random(dtype='float32') state = rg.bit_generator.state n1 = rg.random(size=10, dtype='float32') rg2 = Generator(data.bit_generator()) rg2.bit_generator.state = state n2 = rg2.random(size=10, dtype='float32') assert_((n1 == n2).all()) def test_shuffle(self): rg = self._create_rng().rg original = np.arange(200, 0, -1) permuted = rg.permutation(original) assert_((original != permuted).any()) def test_permutation(self): rg = self._create_rng().rg original = np.arange(200, 0, -1) permuted = rg.permutation(original) assert_((original != permuted).any()) def test_beta(self): rg = self._create_rng().rg vals = rg.beta(2.0, 2.0, 10) assert_(len(vals) == 10) vals = rg.beta(np.array([2.0] * 10), 2.0) assert_(len(vals) == 10) vals = rg.beta(2.0, np.array([2.0] * 10)) assert_(len(vals) == 10) vals = rg.beta(np.array([2.0] * 10), np.array([2.0] * 10)) assert_(len(vals) == 10) vals = rg.beta(np.array([2.0] * 10), np.array([[2.0]] * 10)) assert_(vals.shape == (10, 10)) def test_bytes(self): rg = self._create_rng().rg vals = rg.bytes(10) assert_(len(vals) == 10) def test_chisquare(self): rg = self._create_rng().rg vals = rg.chisquare(2.0, 10) assert_(len(vals) == 10) params_1(rg.chisquare) def test_exponential(self): rg = self._create_rng().rg vals = rg.exponential(2.0, 10) assert_(len(vals) == 10) params_1(rg.exponential) def test_f(self): rg = self._create_rng().rg vals = rg.f(3, 1000, 10) assert_(len(vals) == 10) def test_gamma(self): rg = self._create_rng().rg vals = rg.gamma(3, 2, 10) assert_(len(vals) == 10) def test_geometric(self): rg = self._create_rng().rg vals = rg.geometric(0.5, 10) assert_(len(vals) == 10) params_1(rg.exponential, bounded=True) def test_gumbel(self): rg = self._create_rng().rg vals = rg.gumbel(2.0, 2.0, 10) assert_(len(vals) == 10) def test_laplace(self): rg = self._create_rng().rg vals = rg.laplace(2.0, 2.0, 10) assert_(len(vals) == 10) def test_logitic(self): rg = self._create_rng().rg vals = rg.logistic(2.0, 2.0, 10) assert_(len(vals) == 10) def test_logseries(self): rg = self._create_rng().rg vals = rg.logseries(0.5, 10) assert_(len(vals) == 10) def test_negative_binomial(self): rg = self._create_rng().rg vals = rg.negative_binomial(10, 0.2, 10) assert_(len(vals) == 10) def test_noncentral_chisquare(self): rg = self._create_rng().rg vals = rg.noncentral_chisquare(10, 2, 10) assert_(len(vals) == 10) def test_noncentral_f(self): rg = self._create_rng().rg vals = rg.noncentral_f(3, 1000, 2, 10) assert_(len(vals) == 10) vals = rg.noncentral_f(np.array([3] * 10), 1000, 2) assert_(len(vals) == 10) vals = rg.noncentral_f(3, np.array([1000] * 10), 2) assert_(len(vals) == 10) vals = rg.noncentral_f(3, 1000, np.array([2] * 10)) assert_(len(vals) == 10) def test_normal(self): rg = self._create_rng().rg vals = rg.normal(10, 0.2, 10) assert_(len(vals) == 10) def test_pareto(self): rg = self._create_rng().rg vals = rg.pareto(3.0, 10) assert_(len(vals) == 10) def test_poisson(self): rg = self._create_rng().rg vals = rg.poisson(10, 10) assert_(len(vals) == 10) vals = rg.poisson(np.array([10] * 10)) assert_(len(vals) == 10) params_1(rg.poisson) def test_power(self): rg = self._create_rng().rg vals = rg.power(0.2, 10) assert_(len(vals) == 10) def test_integers(self): rg = self._create_rng().rg vals = rg.integers(10, 20, 10) assert_(len(vals) == 10) def test_rayleigh(self): rg = self._create_rng().rg vals = rg.rayleigh(0.2, 10) assert_(len(vals) == 10) params_1(rg.rayleigh, bounded=True) def test_vonmises(self): rg = self._create_rng().rg vals = rg.vonmises(10, 0.2, 10) assert_(len(vals) == 10) def test_wald(self): rg = self._create_rng().rg vals = rg.wald(1.0, 1.0, 10) assert_(len(vals) == 10) def test_weibull(self): rg = self._create_rng().rg vals = rg.weibull(1.0, 10) assert_(len(vals) == 10) def test_zipf(self): rg = self._create_rng().rg vec_1d = np.arange(2.0, 102.0) vec_2d = np.arange(2.0, 102.0)[None, :] mat = np.arange(2.0, 102.0, 0.01).reshape((100, 100)) vals = rg.zipf(10, 10) assert_(len(vals) == 10) vals = rg.zipf(vec_1d) assert_(len(vals) == 100) vals = rg.zipf(vec_2d) assert_(vals.shape == (1, 100)) vals = rg.zipf(mat) assert_(vals.shape == (100, 100)) def test_hypergeometric(self): rg = self._create_rng().rg vals = rg.hypergeometric(25, 25, 20) assert_(np.isscalar(vals)) vals = rg.hypergeometric(np.array([25] * 10), 25, 20) assert_(vals.shape == (10,)) def test_triangular(self): rg = self._create_rng().rg vals = rg.triangular(-5, 0, 5) assert_(np.isscalar(vals)) vals = rg.triangular(-5, np.array([0] * 10), 5) assert_(vals.shape == (10,)) def test_multivariate_normal(self): rg = self._create_rng().rg mean = [0, 0] cov = [[1, 0], [0, 100]] # diagonal covariance x = rg.multivariate_normal(mean, cov, 5000) assert_(x.shape == (5000, 2)) x_zig = rg.multivariate_normal(mean, cov, 5000) assert_(x.shape == (5000, 2)) x_inv = rg.multivariate_normal(mean, cov, 5000) assert_(x.shape == (5000, 2)) assert_((x_zig != x_inv).any()) def test_multinomial(self): rg = self._create_rng().rg vals = rg.multinomial(100, [1.0 / 3, 2.0 / 3]) assert_(vals.shape == (2,)) vals = rg.multinomial(100, [1.0 / 3, 2.0 / 3], size=10) assert_(vals.shape == (10, 2)) def test_dirichlet(self): rg = self._create_rng().rg s = rg.dirichlet((10, 5, 3), 20) assert_(s.shape == (20, 3)) def test_pickle(self): rg = self._create_rng().rg pick = pickle.dumps(rg) unpick = pickle.loads(pick) assert_(type(rg) == type(unpick)) assert_(comp_state(rg.bit_generator.state, unpick.bit_generator.state)) pick = pickle.dumps(rg) unpick = pickle.loads(pick) assert_(type(rg) == type(unpick)) assert_(comp_state(rg.bit_generator.state, unpick.bit_generator.state)) def test_seed_array(self): data = self._create_rng() if data.seed_vector_bits is None: bitgen_name = data.bit_generator.__name__ pytest.skip(f'Vector seeding is not supported by {bitgen_name}') if data.seed_vector_bits == 32: dtype = np.uint32 else: dtype = np.uint64 seed = np.array([1], dtype=dtype) bg = data.bit_generator(seed) state1 = bg.state bg = data.bit_generator(1) state2 = bg.state assert_(comp_state(state1, state2)) seed = np.arange(4, dtype=dtype) bg = data.bit_generator(seed) state1 = bg.state bg = data.bit_generator(seed[0]) state2 = bg.state assert_(not comp_state(state1, state2)) seed = np.arange(1500, dtype=dtype) bg = data.bit_generator(seed) state1 = bg.state bg = data.bit_generator(seed[0]) state2 = bg.state assert_(not comp_state(state1, state2)) seed = 2 ** np.mod(np.arange(1500, dtype=dtype), data.seed_vector_bits - 1) + 1 bg = data.bit_generator(seed) state1 = bg.state bg = data.bit_generator(seed[0]) state2 = bg.state assert_(not comp_state(state1, state2)) def test_uniform_float(self): bit_generator = self._create_rng().bit_generator rg = Generator(bit_generator(12345)) warmup(rg) state = rg.bit_generator.state r1 = rg.random(11, dtype=np.float32) rg2 = Generator(bit_generator()) warmup(rg2) rg2.bit_generator.state = state r2 = rg2.random(11, dtype=np.float32) assert_array_equal(r1, r2) assert_equal(r1.dtype, np.float32) assert_(comp_state(rg.bit_generator.state, rg2.bit_generator.state)) def test_gamma_floats(self): bit_generator = self._create_rng().bit_generator rg = Generator(bit_generator()) warmup(rg) state = rg.bit_generator.state r1 = rg.standard_gamma(4.0, 11, dtype=np.float32) rg2 = Generator(bit_generator()) warmup(rg2) rg2.bit_generator.state = state r2 = rg2.standard_gamma(4.0, 11, dtype=np.float32) assert_array_equal(r1, r2) assert_equal(r1.dtype, np.float32) assert_(comp_state(rg.bit_generator.state, rg2.bit_generator.state)) def test_normal_floats(self): bit_generator = self._create_rng().bit_generator rg = Generator(bit_generator()) warmup(rg) state = rg.bit_generator.state r1 = rg.standard_normal(11, dtype=np.float32) rg2 = Generator(bit_generator()) warmup(rg2) rg2.bit_generator.state = state r2 = rg2.standard_normal(11, dtype=np.float32) assert_array_equal(r1, r2) assert_equal(r1.dtype, np.float32) assert_(comp_state(rg.bit_generator.state, rg2.bit_generator.state)) def test_normal_zig_floats(self): bit_generator = self._create_rng().bit_generator rg = Generator(bit_generator()) warmup(rg) state = rg.bit_generator.state r1 = rg.standard_normal(11, dtype=np.float32) rg2 = Generator(bit_generator()) warmup(rg2) rg2.bit_generator.state = state r2 = rg2.standard_normal(11, dtype=np.float32) assert_array_equal(r1, r2) assert_equal(r1.dtype, np.float32) assert_(comp_state(rg.bit_generator.state, rg2.bit_generator.state)) def test_output_fill(self): rg = self._create_rng().rg state = rg.bit_generator.state size = (31, 7, 97) existing = np.empty(size) rg.bit_generator.state = state rg.standard_normal(out=existing) rg.bit_generator.state = state direct = rg.standard_normal(size=size) assert_equal(direct, existing) sized = np.empty(size) rg.bit_generator.state = state rg.standard_normal(out=sized, size=sized.shape) existing = np.empty(size, dtype=np.float32) rg.bit_generator.state = state rg.standard_normal(out=existing, dtype=np.float32) rg.bit_generator.state = state direct = rg.standard_normal(size=size, dtype=np.float32) assert_equal(direct, existing) def test_output_filling_uniform(self): rg = self._create_rng().rg state = rg.bit_generator.state size = (31, 7, 97) existing = np.empty(size) rg.bit_generator.state = state rg.random(out=existing) rg.bit_generator.state = state direct = rg.random(size=size) assert_equal(direct, existing) existing = np.empty(size, dtype=np.float32) rg.bit_generator.state = state rg.random(out=existing, dtype=np.float32) rg.bit_generator.state = state direct = rg.random(size=size, dtype=np.float32) assert_equal(direct, existing) def test_output_filling_exponential(self): rg = self._create_rng().rg state = rg.bit_generator.state size = (31, 7, 97) existing = np.empty(size) rg.bit_generator.state = state rg.standard_exponential(out=existing) rg.bit_generator.state = state direct = rg.standard_exponential(size=size) assert_equal(direct, existing) existing = np.empty(size, dtype=np.float32) rg.bit_generator.state = state rg.standard_exponential(out=existing, dtype=np.float32) rg.bit_generator.state = state direct = rg.standard_exponential(size=size, dtype=np.float32) assert_equal(direct, existing) def test_output_filling_gamma(self): rg = self._create_rng().rg state = rg.bit_generator.state size = (31, 7, 97) existing = np.zeros(size) rg.bit_generator.state = state rg.standard_gamma(1.0, out=existing) rg.bit_generator.state = state direct = rg.standard_gamma(1.0, size=size) assert_equal(direct, existing) existing = np.zeros(size, dtype=np.float32) rg.bit_generator.state = state rg.standard_gamma(1.0, out=existing, dtype=np.float32) rg.bit_generator.state = state direct = rg.standard_gamma(1.0, size=size, dtype=np.float32) assert_equal(direct, existing) def test_output_filling_gamma_broadcast(self): rg = self._create_rng().rg state = rg.bit_generator.state size = (31, 7, 97) mu = np.arange(97.0) + 1.0 existing = np.zeros(size) rg.bit_generator.state = state rg.standard_gamma(mu, out=existing) rg.bit_generator.state = state direct = rg.standard_gamma(mu, size=size) assert_equal(direct, existing) existing = np.zeros(size, dtype=np.float32) rg.bit_generator.state = state rg.standard_gamma(mu, out=existing, dtype=np.float32) rg.bit_generator.state = state direct = rg.standard_gamma(mu, size=size, dtype=np.float32) assert_equal(direct, existing) def test_output_fill_error(self): rg = self._create_rng().rg size = (31, 7, 97) existing = np.empty(size) with pytest.raises(TypeError): rg.standard_normal(out=existing, dtype=np.float32) with pytest.raises(ValueError): rg.standard_normal(out=existing[::3]) existing = np.empty(size, dtype=np.float32) with pytest.raises(TypeError): rg.standard_normal(out=existing, dtype=np.float64) existing = np.zeros(size, dtype=np.float32) with pytest.raises(TypeError): rg.standard_gamma(1.0, out=existing, dtype=np.float64) with pytest.raises(ValueError): rg.standard_gamma(1.0, out=existing[::3], dtype=np.float32) existing = np.zeros(size, dtype=np.float64) with pytest.raises(TypeError): rg.standard_gamma(1.0, out=existing, dtype=np.float32) with pytest.raises(ValueError): rg.standard_gamma(1.0, out=existing[::3]) @pytest.mark.parametrize("dtype", DTYPES_BOOL_INT_UINT) def test_integers_broadcast(self, dtype): rg = self._create_rng().rg initial_state = rg.bit_generator.state def reset_state(rng): rng.bit_generator.state = initial_state if dtype == np.bool: upper = 2 lower = 0 else: info = np.iinfo(dtype) upper = int(info.max) + 1 lower = info.min reset_state(rg) rg.bit_generator.state = initial_state a = rg.integers(lower, [upper] * 10, dtype=dtype) reset_state(rg) b = rg.integers([lower] * 10, upper, dtype=dtype) assert_equal(a, b) reset_state(rg) c = rg.integers(lower, upper, size=10, dtype=dtype) assert_equal(a, c) reset_state(rg) d = rg.integers(np.array( [lower] * 10), np.array([upper], dtype=object), size=10, dtype=dtype) assert_equal(a, d) reset_state(rg) e = rg.integers( np.array([lower] * 10), np.array([upper] * 10), size=10, dtype=dtype) assert_equal(a, e) reset_state(rg) a = rg.integers(0, upper, size=10, dtype=dtype) reset_state(rg) b = rg.integers([upper] * 10, dtype=dtype) assert_equal(a, b) @pytest.mark.parametrize("dtype", DTYPES_BOOL_INT_UINT) def test_integers_numpy(self, dtype): rg = self._create_rng().rg high = np.array([1]) low = np.array([0]) out = rg.integers(low, high, dtype=dtype) assert out.shape == (1,) out = rg.integers(low[0], high, dtype=dtype) assert out.shape == (1,) out = rg.integers(low, high[0], dtype=dtype) assert out.shape == (1,) @pytest.mark.parametrize("dtype", DTYPES_BOOL_INT_UINT) def test_integers_broadcast_errors(self, dtype): rg = self._create_rng().rg if dtype == np.bool: upper = 2 lower = 0 else: info = np.iinfo(dtype) upper = int(info.max) + 1 lower = info.min with pytest.raises(ValueError): rg.integers(lower, [upper + 1] * 10, dtype=dtype) with pytest.raises(ValueError): rg.integers(lower - 1, [upper] * 10, dtype=dtype) with pytest.raises(ValueError): rg.integers([lower - 1], [upper] * 10, dtype=dtype) with pytest.raises(ValueError): rg.integers([0], [0], dtype=dtype)
RNG
python
lxml__lxml
benchmark/bench_xslt.py
{ "start": 185, "end": 793 }
class ____(benchbase.TreeBenchMark): @onlylib('lxe') def bench_xslt_document(self, root): transform = self.etree.XSLT(self.etree.XML("""\ <xsl:stylesheet version="1.0" xmlns:l="test" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <l:data>TEST</l:data> <xsl:template match="/"> <l:result> <xsl:for-each select="*/*"> <l:test><xsl:copy-of select="document('')//l:data/text()"/></l:test> </xsl:for-each> </l:result> </xsl:template> </xsl:stylesheet> """)) transform(root) if __name__ == '__main__': benchbase.main(XSLTBenchMark)
XSLTBenchMark
python
pandas-dev__pandas
pandas/errors/__init__.py
{ "start": 22827, "end": 24254 }
class ____(NameError): """ Exception raised by ``query`` or ``eval`` when using an undefined variable name. It will also specify whether the undefined variable is local or not. Parameters ---------- name : str The name of the undefined variable. is_local : bool or None, optional Indicates whether the undefined variable is considered a local variable. If ``True``, the error message specifies it as a local variable. If ``False`` or ``None``, the variable is treated as a non-local name. See Also -------- DataFrame.query : Query the columns of a DataFrame with a boolean expression. DataFrame.eval : Evaluate a string describing operations on DataFrame columns. Examples -------- >>> df = pd.DataFrame({"A": [1, 1, 1]}) >>> df.query("A > x") # doctest: +SKIP ... # UndefinedVariableError: name 'x' is not defined >>> df.query("A > @y") # doctest: +SKIP ... # UndefinedVariableError: local variable 'y' is not defined >>> pd.eval("x + 1") # doctest: +SKIP ... # UndefinedVariableError: name 'x' is not defined """ def __init__(self, name: str, is_local: bool | None = None) -> None: base_msg = f"{name!r} is not defined" if is_local: msg = f"local variable {base_msg}" else: msg = f"name {base_msg}" super().__init__(msg)
UndefinedVariableError
python
arrow-py__arrow
tests/test_locales.py
{ "start": 117580, "end": 121849 }
class ____: def test_format_timeframe(self): assert self.locale._format_timeframe("now", 0) == "剛才" assert self.locale._format_timeframe("second", 1) == "1秒" assert self.locale._format_timeframe("seconds", 30) == "30秒" assert self.locale._format_timeframe("minute", 1) == "1分鐘" assert self.locale._format_timeframe("minutes", 40) == "40分鐘" assert self.locale._format_timeframe("hour", 1) == "1小時" assert self.locale._format_timeframe("hours", 23) == "23小時" assert self.locale._format_timeframe("day", 1) == "1天" assert self.locale._format_timeframe("days", 12) == "12天" assert self.locale._format_timeframe("week", 1) == "1週" assert self.locale._format_timeframe("weeks", 38) == "38週" assert self.locale._format_timeframe("month", 1) == "1個月" assert self.locale._format_timeframe("months", 11) == "11個月" assert self.locale._format_timeframe("year", 1) == "1年" assert self.locale._format_timeframe("years", 12) == "12年" assert self.locale._format_timeframe("second", -1) == "1秒" assert self.locale._format_timeframe("seconds", -30) == "30秒" assert self.locale._format_timeframe("minute", -1) == "1分鐘" assert self.locale._format_timeframe("minutes", -40) == "40分鐘" assert self.locale._format_timeframe("hour", -1) == "1小時" assert self.locale._format_timeframe("hours", -23) == "23小時" assert self.locale._format_timeframe("day", -1) == "1天" assert self.locale._format_timeframe("days", -12) == "12天" assert self.locale._format_timeframe("week", -1) == "1週" assert self.locale._format_timeframe("weeks", -38) == "38週" assert self.locale._format_timeframe("month", -1) == "1個月" assert self.locale._format_timeframe("months", -11) == "11個月" assert self.locale._format_timeframe("year", -1) == "1年" assert self.locale._format_timeframe("years", -12) == "12年" def test_format_relative_now(self): assert self.locale._format_relative("剛才", "now", 0) == "剛才" def test_format_relative_past(self): assert self.locale._format_relative("1秒", "second", 1) == "1秒後" assert self.locale._format_relative("2秒", "seconds", 2) == "2秒後" assert self.locale._format_relative("1分鐘", "minute", 1) == "1分鐘後" assert self.locale._format_relative("2分鐘", "minutes", 2) == "2分鐘後" assert self.locale._format_relative("1小時", "hour", 1) == "1小時後" assert self.locale._format_relative("2小時", "hours", 2) == "2小時後" assert self.locale._format_relative("1天", "day", 1) == "1天後" assert self.locale._format_relative("2天", "days", 2) == "2天後" assert self.locale._format_relative("1週", "week", 1) == "1週後" assert self.locale._format_relative("2週", "weeks", 2) == "2週後" assert self.locale._format_relative("1個月", "month", 1) == "1個月後" assert self.locale._format_relative("2個月", "months", 2) == "2個月後" assert self.locale._format_relative("1年", "year", 1) == "1年後" assert self.locale._format_relative("2年", "years", 2) == "2年後" def test_format_relative_future(self): assert self.locale._format_relative("1秒", "second", -1) == "1秒前" assert self.locale._format_relative("2秒", "seconds", -2) == "2秒前" assert self.locale._format_relative("1分鐘", "minute", -1) == "1分鐘前" assert self.locale._format_relative("2分鐘", "minutes", -2) == "2分鐘前" assert self.locale._format_relative("1小時", "hour", -1) == "1小時前" assert self.locale._format_relative("2小時", "hours", -2) == "2小時前" assert self.locale._format_relative("1天", "day", -1) == "1天前" assert self.locale._format_relative("2天", "days", -2) == "2天前" assert self.locale._format_relative("1週", "week", -1) == "1週前" assert self.locale._format_relative("2週", "weeks", -2) == "2週前" assert self.locale._format_relative("1個月", "month", -1) == "1個月前" assert self.locale._format_relative("2個月", "months", -2) == "2個月前" assert self.locale._format_relative("1年", "year", -1) == "1年前" assert self.locale._format_relative("2年", "years", -2) == "2年前" @pytest.mark.usefixtures("lang_locale")
TestChineseTWLocale
python
pytorch__pytorch
test/inductor/test_compile_subprocess.py
{ "start": 2127, "end": 9227 }
class ____(TestCase): def setUp(self): torch._dynamo.reset() FxCompile._reset_stats() super().setUp() self._stack = contextlib.ExitStack() self._stack.enter_context( patch( "torch._inductor.compile_fx.fx_compile_mode", FxCompileMode.SUBPROCESS, ) ) def tearDown(self): # Check that the test didn't instigate an in-process compile - which # would mean that something about the fx graph failed to serialize. If # some tests are expected to fail then we should probably add a list of # expected failures here. self.assertEqual( FxCompile._compile_stats[type(_InProcessFxCompile)].codegen_and_compile, 0 ) self._stack.close() TestCase.tearDown(self) torch._dynamo.reset() @requires_gpu() @requires_triton() @unittest.skipIf( not IS_BIG_GPU, "Skipping triton backend only since not big GPU (not enough SM)" ) def test_progressive(self): from triton.testing import do_bench from torch._inductor.compile_fx_async import _ProgressiveFxCompile torch._inductor.compile_fx.fx_compile_progressive = True x = torch.randn(1152, 1024, device=GPU_TYPE, dtype=torch.bfloat16) y = torch.randn(1024, 1024, device=GPU_TYPE, dtype=torch.bfloat16) @torch.compile(fullgraph=True, backend="inductor") def optimized(x, y): return (x @ y).relu() _ProgressiveFxCompile._reset_stats() source_codes: list[str] = [] def save_output_code(code: str) -> None: source_codes.append(code) with contextlib.ExitStack() as stack: # When this bug is fixed, remove the cache disabling below assert torch._inductor.compile_fx_async.BUG_CACHES_DONT_WORK_WITH_ASYNC stack.enter_context( torch._inductor.config.patch( autotune_local_cache=False, fx_graph_cache=False ) ) stack.enter_context( mock.patch.object(GraphLowering, "save_output_code", save_output_code) ) stack.enter_context( torch._functorch.config.patch(enable_autograd_cache=False) ) # How long to wait (in seconds) before giving up. TIMEOUT = 300 # If non-None then how often (in seconds) to print a TICK message. TICK_REPORT = None start = time.time() last_report = start while _ProgressiveFxCompile._stat_optimized_runs < 4: time.sleep(0.25) optimized(x, y) now = time.time() if TICK_REPORT is not None and (now - last_report > TICK_REPORT): print(f"*** TICK {int(now - start)}") last_report = now if now - start > TIMEOUT: raise RuntimeError( "Test timed out before producing a progressively optimized compiled artifact." ) self.assertEqual(_ProgressiveFxCompile._stat_optimized_runs, 4) self.assertGreater(_ProgressiveFxCompile._stat_fast_runs, 0) self.assertGreaterEqual(_ProgressiveFxCompile._stat_bg_started, 1) self.assertGreaterEqual(_ProgressiveFxCompile._stat_bg_finished, 1) torch._inductor.compile_fx.fx_compile_progressive = False @torch.compile(fullgraph=True, backend="inductor") def baseline(x, y): return (x @ y).relu() # Warmup baseline(x, y) self.assertGreater( do_bench(lambda: baseline(x, y)), do_bench(lambda: optimized(x, y)) ) self.assertTrue("'max_autotune': True" in source_codes[-1]) @patch("torch._inductor.compile_fx.fx_compile_async", True) def test_async(self): # Test that async+subprocess works. from torch._inductor.compile_fx_async import _AsyncFxCompile @torch.compile(fullgraph=True, backend="inductor") def model_add(x, y): out = x for _ in range(500): out = torch.add(out, y) return out _AsyncFxCompile._reset_stats() with contextlib.ExitStack() as stack: assert torch._inductor.compile_fx_async.BUG_CACHES_DONT_WORK_WITH_ASYNC stack.enter_context( torch._inductor.config.patch( autotune_local_cache=False, fx_graph_cache=False ) ) stack.enter_context( torch._functorch.config.patch(enable_autograd_cache=False) ) # How long to wait (in seconds) before giving up. TIMEOUT = 300 # If non-None then how often (in seconds) to print a TICK message. TICK_REPORT = None start = time.time() last_report = start while True: start_stat_compiled_runs = _AsyncFxCompile._stat_compiled_runs # Sleep a bit so we don't drive the CPU unnecessarily. time.sleep(0.25) x = torch.randn(100, 100, requires_grad=True) y = torch.randn(100, 100, requires_grad=True) # Forward pass output = model_add(x, y) # Backward pass output.sum().backward() if _AsyncFxCompile._stat_compiled_runs - start_stat_compiled_runs == 2: break # DEBUGGING: Print a periodic message so we know we're still # running... now = time.time() if TICK_REPORT is not None and (now - last_report > TICK_REPORT): print(f"*** TICK {int(now - start)}") last_report = now if now - start > TIMEOUT: raise RuntimeError( "Test timed out before producing a compiled artifact." ) self.assertGreater(_AsyncFxCompile._stat_compiled_runs, 1) # Make sure we ran eager at least once. Normally this will be # something like 80. self.assertGreater(_AsyncFxCompile._stat_eager_runs, 0) self.assertEqual(_AsyncFxCompile._stat_bg_started, 2) self.assertEqual(_AsyncFxCompile._stat_bg_finished, 2) if RUN_CPU: class CpuTests(TestSubprocess): common = check_model device = "cpu" copy_tests( inductor.test_torchinductor.CommonTemplate, CpuTests, "cpu", test_failures ) if RUN_GPU and not TEST_WITH_ASAN: class GPUTests(TestSubprocess): common = check_model_gpu device = GPU_TYPE copy_tests( inductor.test_torchinductor.CommonTemplate, GPUTests, GPU_TYPE, test_failures ) if __name__ == "__main__": from torch._inductor.test_case import run_tests if RUN_CPU or RUN_GPU: run_tests(needs="filelock")
TestSubprocess
python
google__jax
jax/_src/monitoring.py
{ "start": 933, "end": 1050 }
class ____(Protocol): def __call__(self, event: str, **kwargs: str | int) -> None: ...
EventListenerWithMetadata
python
kamyu104__LeetCode-Solutions
Python/zero-array-transformation-iv.py
{ "start": 77, "end": 1128 }
class ____(object): def minZeroArray(self, nums, queries): """ :type nums: List[int] :type queries: List[List[int]] :rtype: int """ def binary_search(left, right, check): while left <= right: mid = left + (right-left)//2 if check(mid): right = mid-1 else: left = mid+1 return left def check(l): def valid(arr, target): dp = [False]*(target+1) dp[0] = 1 for i in xrange(len(arr)): dp = [dp[j] or (j-arr[i] >= 0 and dp[j-arr[i]]) for j in xrange(target+1)] return dp[target] return all(valid([queries[j][2] for j in xrange(l) if queries[j][0] <= i <= queries[j][1]], nums[i]) for i in xrange(len(nums))) result = binary_search(0, len(queries), check) return result if result <= len(queries) else -1 # Time: O(q * n * 2^n) # Space: O(n * 2^n) # dp
Solution
python
gevent__gevent
src/greentest/3.10/test_socket.py
{ "start": 84971, "end": 87090 }
class ____(ThreadedRDSSocketTest): def __init__(self, methodName='runTest'): ThreadedRDSSocketTest.__init__(self, methodName=methodName) def setUp(self): super().setUp() self.evt = threading.Event() def testSendAndRecv(self): data, addr = self.serv.recvfrom(self.bufsize) self.assertEqual(self.data, data) self.assertEqual(self.cli_addr, addr) def _testSendAndRecv(self): self.data = b'spam' self.cli.sendto(self.data, 0, (HOST, self.port)) def testPeek(self): data, addr = self.serv.recvfrom(self.bufsize, socket.MSG_PEEK) self.assertEqual(self.data, data) data, addr = self.serv.recvfrom(self.bufsize) self.assertEqual(self.data, data) def _testPeek(self): self.data = b'spam' self.cli.sendto(self.data, 0, (HOST, self.port)) @requireAttrs(socket.socket, 'recvmsg') def testSendAndRecvMsg(self): data, ancdata, msg_flags, addr = self.serv.recvmsg(self.bufsize) self.assertEqual(self.data, data) @requireAttrs(socket.socket, 'sendmsg') def _testSendAndRecvMsg(self): self.data = b'hello ' * 10 self.cli.sendmsg([self.data], (), 0, (HOST, self.port)) def testSendAndRecvMulti(self): data, addr = self.serv.recvfrom(self.bufsize) self.assertEqual(self.data1, data) data, addr = self.serv.recvfrom(self.bufsize) self.assertEqual(self.data2, data) def _testSendAndRecvMulti(self): self.data1 = b'bacon' self.cli.sendto(self.data1, 0, (HOST, self.port)) self.data2 = b'egg' self.cli.sendto(self.data2, 0, (HOST, self.port)) def testSelect(self): r, w, x = select.select([self.serv], [], [], 3.0) self.assertIn(self.serv, r) data, addr = self.serv.recvfrom(self.bufsize) self.assertEqual(self.data, data) def _testSelect(self): self.data = b'select' self.cli.sendto(self.data, 0, (HOST, self.port)) @unittest.skipUnless(HAVE_SOCKET_QIPCRTR, 'QIPCRTR sockets required for this test.')
RDSTest
python
wandb__wandb
wandb/vendor/pygments/lexers/dotnet.py
{ "start": 12300, "end": 14984 }
class ____(RegexLexer): """ For `Boo <http://boo.codehaus.org/>`_ source code. """ name = 'Boo' aliases = ['boo'] filenames = ['*.boo'] mimetypes = ['text/x-boo'] tokens = { 'root': [ (r'\s+', Text), (r'(#|//).*$', Comment.Single), (r'/[*]', Comment.Multiline, 'comment'), (r'[]{}:(),.;[]', Punctuation), (r'\\\n', Text), (r'\\', Text), (r'(in|is|and|or|not)\b', Operator.Word), (r'/(\\\\|\\/|[^/\s])/', String.Regex), (r'@/(\\\\|\\/|[^/])*/', String.Regex), (r'=~|!=|==|<<|>>|[-+/*%=<>&^|]', Operator), (r'(as|abstract|callable|constructor|destructor|do|import|' r'enum|event|final|get|interface|internal|of|override|' r'partial|private|protected|public|return|set|static|' r'struct|transient|virtual|yield|super|and|break|cast|' r'continue|elif|else|ensure|except|for|given|goto|if|in|' r'is|isa|not|or|otherwise|pass|raise|ref|try|unless|when|' r'while|from|as)\b', Keyword), (r'def(?=\s+\(.*?\))', Keyword), (r'(def)(\s+)', bygroups(Keyword, Text), 'funcname'), (r'(class)(\s+)', bygroups(Keyword, Text), 'classname'), (r'(namespace)(\s+)', bygroups(Keyword, Text), 'namespace'), (r'(?<!\.)(true|false|null|self|__eval__|__switch__|array|' r'assert|checked|enumerate|filter|getter|len|lock|map|' r'matrix|max|min|normalArrayIndexing|print|property|range|' r'rawArrayIndexing|required|typeof|unchecked|using|' r'yieldAll|zip)\b', Name.Builtin), (r'"""(\\\\|\\"|.*?)"""', String.Double), (r'"(\\\\|\\"|[^"]*?)"', String.Double), (r"'(\\\\|\\'|[^']*?)'", String.Single), (r'[a-zA-Z_]\w*', Name), (r'(\d+\.\d*|\d*\.\d+)([fF][+-]?[0-9]+)?', Number.Float), (r'[0-9][0-9.]*(ms?|d|h|s)', Number), (r'0\d+', Number.Oct), (r'0x[a-fA-F0-9]+', Number.Hex), (r'\d+L', Number.Integer.Long), (r'\d+', Number.Integer), ], 'comment': [ ('/[*]', Comment.Multiline, '#push'), ('[*]/', Comment.Multiline, '#pop'), ('[^/*]', Comment.Multiline), ('[*/]', Comment.Multiline) ], 'funcname': [ ('[a-zA-Z_]\w*', Name.Function, '#pop') ], 'classname': [ ('[a-zA-Z_]\w*', Name.Class, '#pop') ], 'namespace': [ ('[a-zA-Z_][\w.]*', Name.Namespace, '#pop') ] }
BooLexer
python
google__pytype
pytype/abstract/_instances.py
{ "start": 17819, "end": 26067 }
class ____(_instance_base.Instance, mixin.HasSlots, mixin.PythonDict): """Representation of Python 'dict' objects. It works like builtins.dict, except that, for string keys, it keeps track of what got stored. """ def __init__(self, ctx: "context.Context") -> None: super().__init__(ctx.convert.dict_type, ctx) mixin.HasSlots.init_mixin(self) self.set_native_slot("__contains__", self.contains_slot) self.set_native_slot("__getitem__", self.getitem_slot) self.set_native_slot("__setitem__", self.setitem_slot) self.set_native_slot("pop", self.pop_slot) self.set_native_slot("setdefault", self.setdefault_slot) self.set_native_slot("update", self.update_slot) # Insertion order does matter in some places. # For example: f_locals["__annotations__"] mixin.PythonDict.init_mixin(self, {}) def str_of_constant(self, printer: Callable[[_base.BaseValue], str]) -> str: # self.pyval is only populated for string keys. if not self.is_concrete: return "{...: ...}" pairs = [ f"{name!r}: {' or '.join(_var_map(printer, value))}" for name, value in self.pyval.items() ] return "{" + ", ".join(pairs) + "}" def __repr__(self) -> str: if not hasattr(self, "is_concrete"): return "Dict (not fully initialized)" elif self.is_concrete: return mixin.PythonConstant.__repr__(self) else: return _instance_base.Instance.__repr__(self) def get_fullhash(self, seen=None): if not self.is_concrete: return super().get_fullhash(seen) if seen is None: seen = set() elif id(self) in seen: return self.get_default_fullhash() seen.add(id(self)) return hash( (type(self),) + abstract_utils.get_dict_fullhash_component(self.pyval, seen=seen) ) def getitem_slot( self, node: cfg.CFGNode, name_var: cfg.Variable ) -> tuple[cfg.CFGNode, cfg.Variable]: """Implements the __getitem__ slot.""" results = [] unresolved = False if self.is_concrete: for val in name_var.bindings: try: name = self.ctx.convert.value_to_constant(val.data, str) except abstract_utils.ConversionError: unresolved = True else: try: results.append(self.pyval[name]) except KeyError as e: unresolved = True raise error_types.DictKeyMissing(name) from e node, ret = self.call_pytd(node, "__getitem__", name_var) if unresolved or not self.is_concrete: # We *do* know the overall type of the values through the "V" type # parameter, even if we don't know the exact type of self[name]. So let's # just use the (less accurate) value from pytd. results.append(ret) return node, self.ctx.join_variables(node, results) def merge_instance_type_params( self, node: cfg.CFGNode, name_var: cfg.Variable, value_var: cfg.Variable ) -> None: self.merge_instance_type_parameter(node, abstract_utils.K, name_var) self.merge_instance_type_parameter(node, abstract_utils.V, value_var) def set_str_item( self, node: cfg.CFGNode, name: str, value_var: cfg.Variable ) -> cfg.CFGNode: name_var = self.ctx.convert.build_nonatomic_string(node) self.merge_instance_type_params(node, name_var, value_var) if name in self.pyval: self.pyval[name].PasteVariable(value_var, node) else: self.pyval[name] = value_var return node def setitem( self, node: cfg.CFGNode, name_var: cfg.Variable, value_var: cfg.Variable ) -> None: for val in name_var.bindings: try: name = self.ctx.convert.value_to_constant(val.data, str) except abstract_utils.ConversionError: # Now the dictionary is abstract: We don't know what it contains # anymore. Note that the below is not a variable, so it'll affect # all branches. self.is_concrete = False continue if name in self.pyval: self.pyval[name].PasteVariable(value_var, node) else: self.pyval[name] = value_var def setitem_slot( self, node: cfg.CFGNode, name_var: cfg.Variable, value_var: cfg.Variable ) -> tuple[cfg.CFGNode, cfg.Variable]: """Implements the __setitem__ slot.""" self.setitem(node, name_var, value_var) return self.call_pytd( node, "__setitem__", abstract_utils.abstractify_variable(name_var, self.ctx), abstract_utils.abstractify_variable(value_var, self.ctx), ) def setdefault_slot( self, node: cfg.CFGNode, name_var: cfg.Variable, value_var: cfg.Variable | None = None, ) -> tuple[cfg.CFGNode, cfg.Variable]: if value_var is None: value_var = self.ctx.convert.build_none(node) # We don't have a good way of modelling the exact setdefault behavior - # whether the key already exists might depend on a code path, so setting it # again should depend on an if-splitting condition, but we don't support # negative conditions. self.setitem(node, name_var, value_var) return self.call_pytd(node, "setdefault", name_var, value_var) def contains_slot( self, node: cfg.CFGNode, key_var: cfg.Variable ) -> tuple[cfg.CFGNode, cfg.Variable]: if self.is_concrete: try: str_key = abstract_utils.get_atomic_python_constant(key_var, str) except abstract_utils.ConversionError: value = None else: value = str_key in self.pyval else: value = None return node, self.ctx.convert.build_bool(node, value) def pop_slot( self, node: cfg.CFGNode, key_var, default_var: cfg.Variable | None = None ) -> tuple[cfg.CFGNode, cfg.Variable]: try: str_key = abstract_utils.get_atomic_python_constant(key_var, str) except abstract_utils.ConversionError: self.is_concrete = False if not self.is_concrete: if default_var: return self.call_pytd(node, "pop", key_var, default_var) else: return self.call_pytd(node, "pop", key_var) if default_var: return node, self.pyval.pop(str_key, default_var) else: try: return node, self.pyval.pop(str_key) except KeyError as e: raise error_types.DictKeyMissing(str_key) from e def _set_params_to_any(self, node: cfg.CFGNode) -> None: self.is_concrete = False unsolvable = self.ctx.new_unsolvable(node) for p in (abstract_utils.K, abstract_utils.V): self.merge_instance_type_parameter(node, p, unsolvable) @contextlib.contextmanager def _set_params_to_any_on_failure( self, node: cfg.CFGNode ) -> _Generator[None, None, None]: try: yield except error_types.FailedFunctionCall: self._set_params_to_any(node) raise def update_slot( self, node: cfg.CFGNode, *args, **kwargs ) -> tuple[cfg.CFGNode, cfg.Variable]: if len(args) == 1 and len(args[0].data) == 1: with self._set_params_to_any_on_failure(node): for f in self._super["update"].data: f.underlying.match_args(node, function.Args((f.callself,) + args)) self.update(node, args[0].data[0]) ret = self.ctx.convert.none.to_variable(node) elif args: self.is_concrete = False with self._set_params_to_any_on_failure(node): node, ret = self.call_pytd(node, "update", *args) else: ret = self.ctx.convert.none.to_variable(node) self.update(node, kwargs) return node, ret def update( self, node: cfg.CFGNode, other_dict: Union["Dict", dict[str, cfg.Variable], _base.BaseValue], omit: tuple[str, ...] = (), ) -> None: if isinstance(other_dict, (Dict, dict)): for key, value in other_dict.items(): if key not in omit: self.set_str_item(node, key, value) if ( isinstance(other_dict, _instance_base.Instance) and other_dict.full_name == "builtins.dict" ): self.is_concrete &= other_dict.is_concrete for param in (abstract_utils.K, abstract_utils.V): param_value = other_dict.get_instance_type_parameter(param, node) self.merge_instance_type_parameter(node, param, param_value) elif isinstance(other_dict, _base.BaseValue): self._set_params_to_any(node)
Dict
python
python__mypy
mypyc/test/test_namegen.py
{ "start": 180, "end": 2720 }
class ____(unittest.TestCase): def test_candidate_suffixes(self) -> None: assert candidate_suffixes("foo") == ["", "foo."] assert candidate_suffixes("foo.bar") == ["", "bar.", "foo.bar."] def test_exported_name(self) -> None: assert exported_name("foo") == "foo" assert exported_name("foo.bar") == "foo___bar" def test_make_module_translation_map(self) -> None: assert make_module_translation_map(["foo", "bar"]) == {"foo": "foo.", "bar": "bar."} assert make_module_translation_map(["foo.bar", "foo.baz"]) == { "foo.bar": "bar.", "foo.baz": "baz.", } assert make_module_translation_map(["zar", "foo.bar", "foo.baz"]) == { "foo.bar": "bar.", "foo.baz": "baz.", "zar": "zar.", } assert make_module_translation_map(["foo.bar", "fu.bar", "foo.baz"]) == { "foo.bar": "foo.bar.", "fu.bar": "fu.bar.", "foo.baz": "baz.", } assert make_module_translation_map(["foo", "foo.foo", "bar.foo", "bar.foo.bar.foo"]) == { "foo": "foo.", "foo.foo": "foo.foo.", "bar.foo": "bar.foo.", "bar.foo.bar.foo": "foo.bar.foo.", } def test_name_generator(self) -> None: g = NameGenerator([["foo", "foo.zar"]]) assert g.private_name("foo", "f") == "foo___f" assert g.private_name("foo", "C.x.y") == "foo___C___x___y" assert g.private_name("foo", "C.x.y") == "foo___C___x___y" assert g.private_name("foo.zar", "C.x.y") == "zar___C___x___y" assert g.private_name("foo", "C.x_y") == "foo___C___x_y" assert g.private_name("foo", "C_x_y") == "foo___C_x_y" assert g.private_name("foo", "C_x_y") == "foo___C_x_y" assert g.private_name("foo", "___") == "foo______3_" g = NameGenerator([["foo.zar"]]) assert g.private_name("foo.zar", "f") == "f" def test_name_generator_with_separate(self) -> None: g = NameGenerator([["foo", "foo.zar"]], separate=True) assert g.private_name("foo", "f") == "foo___f" assert g.private_name("foo", "C.x.y") == "foo___C___x___y" assert g.private_name("foo.zar", "C.x.y") == "foo___zar___C___x___y" assert g.private_name("foo", "C.x_y") == "foo___C___x_y" assert g.private_name("foo", "___") == "foo______3_" g = NameGenerator([["foo.zar"]], separate=True) assert g.private_name("foo.zar", "f") == "foo___zar___f"
TestNameGen
python
falconry__falcon
tests/test_error_handlers.py
{ "start": 1322, "end": 8466 }
class ____: def test_caught_error(self, client): client.app.add_error_handler(Exception, capture_error) result = client.simulate_get() assert result.text == 'error: Plain Exception' result = client.simulate_head() assert result.status_code == 723 assert not result.content @pytest.mark.parametrize( 'get_headers, resp_content_type, resp_start', [ (None, constants.MEDIA_JSON, '{"'), ({'accept': constants.MEDIA_JSON}, constants.MEDIA_JSON, '{"'), ({'accept': constants.MEDIA_XML}, constants.MEDIA_XML, '<?xml'), ], ) def test_uncaught_python_error( self, client, get_headers, resp_content_type, resp_start ): client.app.resp_options.xml_error_serialization = True result = client.simulate_get(headers=get_headers) assert result.status_code == 500 assert result.headers['content-type'] == resp_content_type assert result.text.startswith(resp_start) def test_caught_error_async(self, asgi): if not asgi: pytest.skip('Test only applies to ASGI') app = falcon.asgi.App() app.add_route('/', ErroredClassResource()) app.add_error_handler(Exception, capture_error_async) client = testing.TestClient(app) result = client.simulate_get() assert result.text == 'error: Plain Exception' result = client.simulate_head() assert result.status_code == 723 assert not result.content def test_uncaught_error(self, client): client.app._error_handlers.clear() client.app.add_error_handler(CustomException, capture_error) with pytest.raises(Exception): client.simulate_get() def test_uncaught_error_else(self, client): client.app._error_handlers.clear() with pytest.raises(Exception): client.simulate_get() def test_converted_error(self, client): client.app.add_error_handler(CustomException) result = client.simulate_delete() assert result.status_code == 792 assert result.json['title'] == 'Internet crashed!' def test_handle_not_defined(self, client): with pytest.raises(AttributeError): client.app.add_error_handler(CustomBaseException) def test_subclass_error(self, client): client.app.add_error_handler(CustomBaseException, capture_error) result = client.simulate_delete() assert result.status_code == 723 assert result.text == 'error: CustomException' def test_error_precedence_duplicate(self, client): client.app.add_error_handler(Exception, capture_error) client.app.add_error_handler(Exception, handle_error_first) result = client.simulate_get() assert result.text == 'first error handler' def test_error_precedence_subclass(self, client): client.app.add_error_handler(Exception, capture_error) client.app.add_error_handler(CustomException, handle_error_first) result = client.simulate_delete() assert result.status_code == 200 assert result.text == 'first error handler' result = client.simulate_get() assert result.status_code == 723 assert result.text == 'error: Plain Exception' def test_error_precedence_subclass_order_indifference(self, client): client.app.add_error_handler(CustomException, handle_error_first) client.app.add_error_handler(Exception, capture_error) result = client.simulate_delete() assert result.status_code == 200 assert result.text == 'first error handler' @pytest.mark.parametrize( 'exceptions', [ (Exception, CustomException), [Exception, CustomException], ], ) def test_handler_multiple_exception_iterable(self, client, exceptions): client.app.add_error_handler(exceptions, capture_error) result = client.simulate_get() assert result.status_code == 723 result = client.simulate_delete() assert result.status_code == 723 def test_handler_single_exception_iterable(self, client): def exception_list_generator(): yield CustomException client.app.add_error_handler(exception_list_generator(), capture_error) result = client.simulate_delete() assert result.status_code == 723 @pytest.mark.parametrize( 'exceptions', [ NotImplemented, 'Hello, world!', frozenset([ZeroDivisionError, int, NotImplementedError]), [float, float], ], ) def test_invalid_add_exception_handler_input(self, client, exceptions): with pytest.raises(TypeError): client.app.add_error_handler(exceptions, capture_error) def test_handler_signature_shim(self, util): def check_args(ex, req, resp): assert isinstance(ex, BaseException) assert isinstance(req, falcon.Request) assert isinstance(resp, falcon.Response) def legacy_handler1(ex, req, resp, params): check_args(ex, req, resp) def legacy_handler2(error_obj, request, response, params): check_args(error_obj, request, response) def legacy_handler3(err, rq, rs, prms): check_args(err, rq, rs) app = util.create_app(asgi=False) app.add_route('/', ErroredClassResource()) client = testing.TestClient(app) with pytest.warns(DeprecatedWarning, match='deprecated signature'): client.app.add_error_handler(Exception, legacy_handler1) with pytest.warns(DeprecatedWarning, match='deprecated signature'): client.app.add_error_handler(CustomBaseException, legacy_handler2) with pytest.warns(DeprecatedWarning, match='deprecated signature'): client.app.add_error_handler(CustomException, legacy_handler3) client.simulate_delete() client.simulate_get() client.simulate_head() def test_handler_must_be_coroutine_for_asgi(self, util): app = util.create_app(True) with util.disable_asgi_non_coroutine_wrapping(): with pytest.raises(ValueError): app.add_error_handler(Exception, capture_error) def test_catch_http_no_route_error(self, asgi, util): class Resource: def on_get(self, req, resp): raise falcon.HTTPNotFound() def capture_error(req, resp, ex, params): resp.set_header('X-name', ex.__class__.__name__) raise ex app = util.create_app(asgi) app.add_route('/', Resource()) app.add_error_handler(falcon.HTTPError, capture_error) client = testing.TestClient(app) result = client.simulate_get('/') assert result.status_code == 404 assert result.headers['X-name'] == 'HTTPNotFound' result = client.simulate_get('/404') assert result.status_code == 404 assert result.headers['X-name'] == 'HTTPRouteNotFound'
TestErrorHandler
python
huggingface__transformers
tests/trainer/test_trainer_distributed_worker_seed.py
{ "start": 1046, "end": 1455 }
class ____(nn.Module): def __init__(self): super().__init__() self.fc = nn.Linear(3, 1) def forward(self, x): local_tensor = torch.tensor(x, device=torch_device) gathered = gather_from_all_gpus(local_tensor, dist.get_world_size()) assert not all(torch.allclose(t, gathered[0]) for t in gathered[1:]) y = self.fc(x) return (y.mean(), y)
DummyModel
python
airbytehq__airbyte
airbyte-integrations/connectors/source-outbrain-amplify/source_outbrain_amplify/source.py
{ "start": 35417, "end": 38394 }
class ____(OutbrainAmplifyStream, HttpSubStream): primary_key = None def __init__(self, authenticator, config, parent: Marketers, **kwargs): super().__init__(parent=parent, **kwargs) self.config = config self._authenticator = authenticator self._session = requests.sessions.Session() def request_params( self, stream_state: Mapping[str, Any], stream_slice: Mapping[str, any] = None, next_page_token: Mapping[str, Any] = None ) -> MutableMapping[str, Any]: return {} def next_page_token(self, response: requests.Response) -> Optional[Mapping[str, Any]]: return None def stream_slices( self, sync_mode: SyncMode.full_refresh, cursor_field: List[str] = None, stream_state: Mapping[str, Any] = None ) -> Iterable[Optional[Mapping[str, Any]]]: parent_stream_slices = self.parent.stream_slices( sync_mode=SyncMode.full_refresh, cursor_field=cursor_field, stream_state=stream_state ) for stream_slice in parent_stream_slices: parent_records = self.parent.read_records( sync_mode=SyncMode.full_refresh, cursor_field=cursor_field, stream_slice=stream_slice, stream_state=stream_state ) for record in parent_records: yield {"marketer_id": record.get("id")} def parse_response( self, response: requests.Response, stream_state: Mapping[str, Any], stream_slice: Mapping[str, Any] = None, next_page_token: Mapping[str, Any] = None, ) -> Iterable[Mapping]: if response.json(): for fetched in response.json().get("campaignResults"): for x in fetched.get("results"): x["marketer_id"] = stream_slice["marketer_id"] x["campaign_id"] = fetched.get("campaignId") yield x def path( self, stream_state: Mapping[str, Any] = None, stream_slice: Mapping[str, Any] = None, next_page_token: Mapping[str, Any] = None ) -> str: stream_start, stream_end = self._get_time_interval(self.config.get("start_date"), self.config.get("end_date")) stream_conversion_count = self._get_bool_conversion_count_by_click_date( self.config.get("conversion_count", DEFAULT_REPORT_CONVERSION_COUNT_BY_CLICK_DATE) ) return ( f"reports/marketers/{stream_slice['marketer_id']}/campaigns/platforms?from=" + str(stream_start.date()) + "&to=" + str(stream_end.date()) + "&limit=500" + "&includeVideoStats=true" + "&conversionsByClickDate=" + str(stream_conversion_count) ) # Retrieve geo performance statistics for a Marketer. # The API in this sub-section allows retrieving performance statistics by geographic breakdown at different levels: country, region, and subregion.
PerformanceReportMarketersCampaignsByPlatforms
python
google__pytype
pytype_extensions/instrumentation_for_testing_test.py
{ "start": 1347, "end": 1666 }
class ____(i4t.ProductionType[NoCtor]): def __init__(self): self.state = 8 def Mul100(self, i): return self.state * i * 105 FakeNoCtorInitNoArgsSealed = FakeNoCtorInitNoArgsUnsealed.SealType() # When access to instrumented_type is not needed. @i4t.SealAsProductionType(NoCtor)
FakeNoCtorInitNoArgsUnsealed
python
wandb__wandb
wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/dirsnapshot.py
{ "start": 5485, "end": 9319 }
class ____(object): """ A snapshot of stat information of files in a directory. :param path: The directory path for which a snapshot should be taken. :type path: ``str`` :param recursive: ``True`` if the entire directory tree should be included in the snapshot; ``False`` otherwise. :type recursive: ``bool`` :param walker_callback: .. deprecated:: 0.7.2 :param stat: Use custom stat function that returns a stat structure for path. Currently only st_dev, st_ino, st_mode and st_mtime are needed. A function with the signature ``walker_callback(path, stat_info)`` which will be called for every entry in the directory tree. :param listdir: Use custom listdir function. See ``os.listdir`` for details. """ def __init__(self, path, recursive=True, walker_callback=(lambda p, s: None), stat=default_stat, listdir=os.listdir): self._stat_info = {} self._inode_to_path = {} st = stat(path) self._stat_info[path] = st self._inode_to_path[(st.st_ino, st.st_dev)] = path def walk(root): try: paths = [os.path.join(root, name) for name in listdir(root)] except OSError as e: # Directory may have been deleted between finding it in the directory # list of its parent and trying to delete its contents. If this # happens we treat it as empty. if e.errno == errno.ENOENT: return else: raise entries = [] for p in paths: try: entries.append((p, stat(p))) except OSError: continue for _ in entries: yield _ if recursive: for path, st in entries: if S_ISDIR(st.st_mode): for _ in walk(path): yield _ for p, st in walk(path): i = (st.st_ino, st.st_dev) self._inode_to_path[i] = p self._stat_info[p] = st walker_callback(p, st) @property def paths(self): """ Set of file/directory paths in the snapshot. """ return set(self._stat_info.keys()) def path(self, id): """ Returns path for id. None if id is unknown to this snapshot. """ return self._inode_to_path.get(id) def inode(self, path): """ Returns an id for path. """ st = self._stat_info[path] return (st.st_ino, st.st_dev) def isdir(self, path): return S_ISDIR(self._stat_info[path].st_mode) def mtime(self, path): return self._stat_info[path].st_mtime def stat_info(self, path): """ Returns a stat information object for the specified path from the snapshot. Attached information is subject to change. Do not use unless you specify `stat` in constructor. Use :func:`inode`, :func:`mtime`, :func:`isdir` instead. :param path: The path for which stat information should be obtained from a snapshot. """ return self._stat_info[path] def __sub__(self, previous_dirsnap): """Allow subtracting a DirectorySnapshot object instance from another. :returns: A :class:`DirectorySnapshotDiff` object. """ return DirectorySnapshotDiff(previous_dirsnap, self) def __str__(self): return self.__repr__() def __repr__(self): return str(self._stat_info)
DirectorySnapshot
python
numba__numba
numba/cuda/stubs.py
{ "start": 6622, "end": 6839 }
class ____(Stub): ''' A memory fence at device level ''' _description_ = '<threadfence()>' #------------------------------------------------------------------------------- # bit manipulation
threadfence
python
apache__airflow
providers/apache/hive/src/airflow/providers/apache/hive/operators/hive_stats.py
{ "start": 1301, "end": 7109 }
class ____(BaseOperator): """ Gather partition statistics and insert them into MySQL. Statistics are gathered with a dynamically generated Presto query and inserted with this format. Stats overwrite themselves if you rerun the same date/partition. .. code-block:: sql CREATE TABLE hive_stats ( ds VARCHAR(16), table_name VARCHAR(500), metric VARCHAR(200), value BIGINT ); :param metastore_conn_id: Reference to the :ref:`Hive Metastore connection id <howto/connection:hive_metastore>`. :param table: the source table, in the format ``database.table_name``. (templated) :param partition: the source partition. (templated) :param extra_exprs: dict of expression to run against the table where keys are metric names and values are Presto compatible expressions :param excluded_columns: list of columns to exclude, consider excluding blobs, large json columns, ... :param assignment_func: a function that receives a column name and a type, and returns a dict of metric names and an Presto expressions. If None is returned, the global defaults are applied. If an empty dictionary is returned, no stats are computed for that column. """ template_fields: Sequence[str] = ("table", "partition", "ds", "dttm") ui_color = "#aff7a6" def __init__( self, *, table: str, partition: Any, extra_exprs: dict[str, Any] | None = None, excluded_columns: list[str] | None = None, assignment_func: Callable[[str, str], dict[Any, Any] | None] | None = None, metastore_conn_id: str = "metastore_default", presto_conn_id: str = "presto_default", mysql_conn_id: str = "airflow_db", ds: str = "{{ ds }}", dttm: str = "{{ logical_date.isoformat() }}", **kwargs: Any, ) -> None: super().__init__(**kwargs) self.table = table self.partition = partition self.extra_exprs = extra_exprs or {} self.excluded_columns: list[str] = excluded_columns or [] self.metastore_conn_id = metastore_conn_id self.presto_conn_id = presto_conn_id self.mysql_conn_id = mysql_conn_id self.assignment_func = assignment_func self.ds = ds self.dttm = dttm def get_default_exprs(self, col: str, col_type: str) -> dict[Any, Any]: """Get default expressions.""" if col in self.excluded_columns: return {} exp = {(col, "non_null"): f"COUNT({col})"} if col_type in {"double", "int", "bigint", "float"}: exp[(col, "sum")] = f"SUM({col})" exp[(col, "min")] = f"MIN({col})" exp[(col, "max")] = f"MAX({col})" exp[(col, "avg")] = f"AVG({col})" elif col_type == "boolean": exp[(col, "true")] = f"SUM(CASE WHEN {col} THEN 1 ELSE 0 END)" exp[(col, "false")] = f"SUM(CASE WHEN NOT {col} THEN 1 ELSE 0 END)" elif col_type == "string": exp[(col, "len")] = f"SUM(CAST(LENGTH({col}) AS BIGINT))" exp[(col, "approx_distinct")] = f"APPROX_DISTINCT({col})" return exp def execute(self, context: Context) -> None: metastore = HiveMetastoreHook(metastore_conn_id=self.metastore_conn_id) table = metastore.get_table(table_name=self.table) field_types = {col.name: col.type for col in table.sd.cols} exprs: Any = {("", "count"): "COUNT(*)"} for col, col_type in list(field_types.items()): if self.assignment_func: assign_exprs = self.assignment_func(col, col_type) if assign_exprs is None: assign_exprs = self.get_default_exprs(col, col_type) else: assign_exprs = self.get_default_exprs(col, col_type) exprs.update(assign_exprs) exprs.update(self.extra_exprs) exprs_str = ",\n ".join(f"{v} AS {k[0]}__{k[1]}" for k, v in exprs.items()) where_clause_ = [f"{k} = '{v}'" for k, v in self.partition.items()] where_clause = " AND\n ".join(where_clause_) sql = f"SELECT {exprs_str} FROM {self.table} WHERE {where_clause};" presto = PrestoHook(presto_conn_id=self.presto_conn_id) self.log.info("Executing SQL check: %s", sql) row = presto.get_first(sql) self.log.info("Record: %s", row) if not row: raise AirflowException("The query returned None") part_json = json.dumps(self.partition, sort_keys=True) self.log.info("Deleting rows from previous runs if they exist") mysql = MySqlHook(self.mysql_conn_id) sql = f""" SELECT 1 FROM hive_stats WHERE table_name='{self.table}' AND partition_repr='{part_json}' AND dttm='{self.dttm}' LIMIT 1; """ if mysql.get_records(sql): sql = f""" DELETE FROM hive_stats WHERE table_name='{self.table}' AND partition_repr='{part_json}' AND dttm='{self.dttm}'; """ mysql.run(sql) self.log.info("Pivoting and loading cells into the Airflow db") rows = [ (self.ds, self.dttm, self.table, part_json) + (r[0][0], r[0][1], r[1]) for r in zip(exprs, row) ] mysql.insert_rows( table="hive_stats", rows=rows, target_fields=[ "ds", "dttm", "table_name", "partition_repr", "col", "metric", "value", ], )
HiveStatsCollectionOperator
python
walkccc__LeetCode
solutions/2383. Minimum Hours of Training to Win a Competition/2383.py
{ "start": 0, "end": 806 }
class ____: def minNumberOfHours( self, initialEnergy: int, initialExperience: int, energy: list[int], experience: list[int], ) -> int: return (self._getRequiredEnergy(initialEnergy, energy) + self._getRequiredExperience(initialExperience, experience)) def _getRequiredEnergy(self, initialEnergy: int, energy: list[int]) -> int: return max(0, sum(energy) + 1 - initialEnergy) def _getRequiredExperience( self, currentExperience: int, experience: list[int], ) -> int: requiredExperience = 0 for e in experience: if e >= currentExperience: requiredExperience += e + 1 - currentExperience currentExperience += e + 1 - currentExperience currentExperience += e return requiredExperience
Solution
python
doocs__leetcode
solution/1000-1099/1003.Check If Word Is Valid After Substitutions/Solution.py
{ "start": 0, "end": 252 }
class ____: def isValid(self, s: str) -> bool: if len(s) % 3: return False t = [] for c in s: t.append(c) if ''.join(t[-3:]) == 'abc': t[-3:] = [] return not t
Solution
python
tensorflow__tensorflow
tensorflow/python/framework/meta_graph_test.py
{ "start": 37808, "end": 39933 }
class ____(test.TestCase): @test_util.run_deprecated_v1 def testMetricsCollection(self): def _enqueue_vector(sess, queue, values, shape=None): if not shape: shape = (1, len(values)) dtype = queue.dtypes[0] sess.run( queue.enqueue(constant_op.constant( values, dtype=dtype, shape=shape))) meta_graph_filename = os.path.join( _TestDir("metrics_export"), "meta_graph.pb") graph = ops.Graph() with self.session(graph=graph) as sess: values_queue = data_flow_ops.FIFOQueue( 4, dtypes.float32, shapes=(1, 2)) _enqueue_vector(sess, values_queue, [0, 1]) _enqueue_vector(sess, values_queue, [-4.2, 9.1]) _enqueue_vector(sess, values_queue, [6.5, 0]) _enqueue_vector(sess, values_queue, [-3.2, 4.0]) values = values_queue.dequeue() _, update_op = metrics.mean(values) initializer = variables.local_variables_initializer() self.evaluate(initializer) self.evaluate(update_op) meta_graph.export_scoped_meta_graph( filename=meta_graph_filename, graph=graph) # Verifies that importing a meta_graph with LOCAL_VARIABLES collection # works correctly. graph = ops.Graph() with self.session(graph=graph) as sess: meta_graph.import_scoped_meta_graph(meta_graph_filename) initializer = variables.local_variables_initializer() self.evaluate(initializer) # Verifies that importing an old meta_graph where "local_variables" # collection is of node_list type works, but cannot build initializer # with the collection. graph = ops.Graph() with self.session(graph=graph) as sess: meta_graph.import_scoped_meta_graph( test.test_src_dir_path( "python/framework/testdata/metrics_export_meta_graph.pb")) self.assertEqual(len(ops.get_collection(ops.GraphKeys.LOCAL_VARIABLES)), 2) with self.assertRaisesRegex( AttributeError, "has no attribute 'initializer'" ): initializer = variables.local_variables_initializer()
MetaGraphWithVariableScopeTest
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/pipelines/config.py
{ "start": 1892, "end": 2272 }
class ____(graphene.ObjectType): field_name = graphene.NonNull(graphene.String) class Meta: name = "EvaluationStackPathEntry" def __init__(self, field_name): self._field_name = check.str_param(field_name, "field_name") super().__init__() def resolve_field_name(self, _info): return self._field_name
GrapheneEvaluationStackPathEntry
python
ray-project__ray
python/ray/air/config.py
{ "start": 12716, "end": 14472 }
class ____: """Configuration related to failure handling of each training/tuning run. Args: max_failures: Tries to recover a run at least this many times. Will recover from the latest checkpoint if present. Setting to -1 will lead to infinite recovery retries. Setting to 0 will disable retries. Defaults to 0. fail_fast: Whether to fail upon the first error. If fail_fast='raise' provided, the original error during training will be immediately raised. fail_fast='raise' can easily leak resources and should be used with caution. """ max_failures: int = 0 fail_fast: Union[bool, str] = False def __post_init__(self): # Same check as in TuneController if not (isinstance(self.fail_fast, bool) or self.fail_fast.upper() == "RAISE"): raise ValueError( "fail_fast must be one of {bool, 'raise'}. " f"Got {self.fail_fast}." ) # Same check as in tune.run if self.fail_fast and self.max_failures != 0: raise ValueError( f"max_failures must be 0 if fail_fast={repr(self.fail_fast)}." ) def __repr__(self): return _repr_dataclass(self) def _repr_html_(self): return Template("scrollableTable.html.j2").render( table=tabulate( { "Setting": ["Max failures", "Fail fast"], "Value": [self.max_failures, self.fail_fast], }, tablefmt="html", showindex=False, headers="keys", ), max_height="none", ) @dataclass @PublicAPI(stability="stable")
FailureConfig
python
great-expectations__great_expectations
great_expectations/metrics/column/descriptive_stats.py
{ "start": 305, "end": 379 }
class ____(MetricResult[DescriptiveStats]): ...
ColumnDescriptiveStatsResult
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chart_points04.py
{ "start": 315, "end": 1673 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chart_points04.xlsx") def test_create_file(self): """Test the creation of an XlsxWriter file with point formatting.""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() chart = workbook.add_chart({"type": "scatter"}) chart.axis_ids = [48542464, 46807296] 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", "points": [{"fill": {"color": "red"}}, {"fill": {"color": "yellow"}}], } ) chart.add_series( { "categories": "=Sheet1!$A$1:$A$5", "values": "=Sheet1!$C$1:$C$5", "points": [None, None, {"fill": {"color": "yellow"}}], } ) worksheet.insert_chart("E9", chart) workbook.close() self.assertExcelEqual()
TestCompareXLSXFiles
python
allegroai__clearml
clearml/backend_api/services/v2_23/tasks.py
{ "start": 245578, "end": 247757 }
class ____(Request): """ Delete models from task :param task: ID of the task :type task: str :param models: The list of models to delete :type models: Sequence[dict] """ _service = "tasks" _action = "delete_models" _version = "2.23" _schema = { "definitions": { "model_type_enum": {"enum": ["input", "output"], "type": "string"} }, "properties": { "models": { "description": "The list of models to delete", "items": { "properties": { "name": { "description": "The task model name", "type": "string", }, "type": { "$ref": "#/definitions/model_type_enum", "description": "The task model type", }, }, "required": ["name", "type"], "type": "object", }, "type": "array", }, "task": {"description": "ID of the task", "type": "string"}, }, "required": ["task", "models"], "type": "object", } def __init__(self, task, models, **kwargs): super(DeleteModelsRequest, self).__init__(**kwargs) self.task = task self.models = models @schema_property("task") def task(self): return self._property_task @task.setter def task(self, value): if value is None: self._property_task = None return self.assert_isinstance(value, "task", six.string_types) self._property_task = value @schema_property("models") def models(self): return self._property_models @models.setter def models(self, value): if value is None: self._property_models = None return self.assert_isinstance(value, "models", (list, tuple)) self.assert_isinstance(value, "models", (dict,), is_array=True) self._property_models = value
DeleteModelsRequest
python
getsentry__sentry
tests/sentry/workflow_engine/models/test_json_config_base.py
{ "start": 3691, "end": 7141 }
class ____(JSONConfigBaseTest, APITestCase): def setUp(self) -> None: super().setUp() self.metric_alert = self.create_alert_rule(threshold_period=1) @dataclass(frozen=True) class TestGroupType(GroupType): type_id = 3 slug = "test_metric_issue" description = "Metric alert fired" category = GroupCategory.METRIC_ALERT.value category_v2 = GroupCategory.METRIC.value detector_settings = DetectorSettings( config_schema=MetricIssue.detector_settings.config_schema, ) def test_detector_correct_schema(self) -> None: self.create_detector( name=self.metric_alert.name, project_id=self.project.id, type="test_metric_issue", owner_user_id=self.metric_alert.user_id, config={ "threshold_period": self.metric_alert.threshold_period, "comparison_delta": self.metric_alert.comparison_delta, "detection_type": self.metric_alert.detection_type, "sensitivity": self.metric_alert.sensitivity, "seasonality": self.metric_alert.seasonality, }, ) def test_empty_config(self) -> None: with pytest.raises(ValidationError): self.create_detector( name=self.metric_alert.name, project_id=self.project.id, type="test_metric_issue", owner_user_id=self.metric_alert.user_id, config={}, ) def test_no_config(self) -> None: with pytest.raises(ValidationError): self.create_detector( name=self.metric_alert.name, project_id=self.project.id, type="test_metric_issue", owner_user_id=self.metric_alert.user_id, ) def test_incorrect_config(self) -> None: with pytest.raises(ValidationError): self.create_detector( name=self.metric_alert.name, project_id=self.project.id, type="test_metric_issue", owner_user_id=self.metric_alert.user_id, config=["some", "stuff"], ) def test_mismatched_schema(self) -> None: with pytest.raises(ValidationError): self.create_detector( name=self.metric_alert.name, project_id=self.project.id, type="test_metric_issue", owner_user_id=self.metric_alert.user_id, config={ "comparison_delta": "matcha", "detection_type": self.metric_alert.detection_type, }, ) def test_missing_required(self) -> None: with pytest.raises(ValidationError): self.create_detector( name=self.metric_alert.name, project_id=self.project.id, type="test_metric_issue", owner_user_id=self.metric_alert.user_id, config={ "threshold_period": self.metric_alert.threshold_period, "comparison_delta": self.metric_alert.comparison_delta, "sensitivity": self.metric_alert.sensitivity, "seasonality": self.metric_alert.seasonality, }, )
TestMetricIssueDetectorConfig
python
hyperopt__hyperopt
hyperopt/exceptions.py
{ "start": 205, "end": 399 }
class ____(ValueError): """Non trial-like object used as Trial""" def __init__(self, msg, obj): ValueError.__init__(self, msg + " " + str(obj)) self.obj = obj
InvalidTrial
python
numba__numba
numba/cuda/nvvmutils.py
{ "start": 7337, "end": 8295 }
class ____(object): def __init__(self, builder): self.builder = builder def tid(self, xyz): return call_sreg(self.builder, 'tid.%s' % xyz) def ctaid(self, xyz): return call_sreg(self.builder, 'ctaid.%s' % xyz) def ntid(self, xyz): return call_sreg(self.builder, 'ntid.%s' % xyz) def nctaid(self, xyz): return call_sreg(self.builder, 'nctaid.%s' % xyz) def getdim(self, xyz): i64 = ir.IntType(64) tid = self.builder.sext(self.tid(xyz), i64) ntid = self.builder.sext(self.ntid(xyz), i64) nctaid = self.builder.sext(self.ctaid(xyz), i64) res = self.builder.add(self.builder.mul(ntid, nctaid), tid) return res def get_global_id(builder, dim): sreg = SRegBuilder(builder) it = (sreg.getdim(xyz) for xyz in 'xyz') seq = list(itertools.islice(it, None, dim)) if dim == 1: return seq[0] else: return seq
SRegBuilder
python
RaRe-Technologies__gensim
gensim/test/test_fasttext.py
{ "start": 44878, "end": 51693 }
class ____(unittest.TestCase): maxDiff = None model_structural_sanity = TestFastTextModel.model_structural_sanity def setUp(self): # # $ echo "quick brown fox jumps over lazy dog" | ./fasttext print-word-vectors gensim/test/test_data/toy-model.bin # noqa: E501 # expected = { u"quick": [0.023393, 0.11499, 0.11684, -0.13349, 0.022543], u"brown": [0.015288, 0.050404, -0.041395, -0.090371, 0.06441], u"fox": [0.061692, 0.082914, 0.020081, -0.039159, 0.03296], u"jumps": [0.070107, 0.081465, 0.051763, 0.012084, 0.0050402], u"over": [0.055023, 0.03465, 0.01648, -0.11129, 0.094555], u"lazy": [-0.022103, -0.020126, -0.033612, -0.049473, 0.0054174], u"dog": [0.084983, 0.09216, 0.020204, -0.13616, 0.01118], } self.oov_expected = { word: np.array(arr, dtype=np.float32) for word, arr in expected.items() } def test_in_vocab(self): """Test for correct representation of in-vocab words.""" native = load_native() with utils.open(datapath('toy-model.vec'), 'r', encoding='utf-8') as fin: expected = dict(load_vec(fin)) for word, expected_vector in expected.items(): actual_vector = native.wv.get_vector(word) self.assertTrue(np.allclose(expected_vector, actual_vector, atol=1e-5)) self.model_structural_sanity(native) def test_out_of_vocab(self): """Test for correct representation of out-of-vocab words.""" native = load_native() for word, expected_vector in self.oov_expected.items(): actual_vector = native.wv.get_vector(word) self.assertTrue(np.allclose(expected_vector, actual_vector, atol=1e-5)) self.model_structural_sanity(native) def test_sanity(self): """Compare models trained on toy data. They should be equal.""" trained = train_gensim() native = load_native() self.assertEqual(trained.wv.bucket, native.wv.bucket) # # Only if match_gensim=True in init_post_load # # self.assertEqual(trained.bucket, native.bucket) compare_wv(trained.wv, native.wv, self) compare_vocabulary(trained, native, self) compare_nn(trained, native, self) self.model_structural_sanity(trained) self.model_structural_sanity(native) def test_continuation_native(self): """Ensure that training has had a measurable effect.""" native = load_native() self.model_structural_sanity(native) # # Pick a word that is in both corpuses. # Its vectors should be different between training runs. # word = 'society' old_vector = native.wv.get_vector(word).tolist() native.train(list_corpus, total_examples=len(list_corpus), epochs=native.epochs) new_vector = native.wv.get_vector(word).tolist() self.assertNotEqual(old_vector, new_vector) self.model_structural_sanity(native) def test_continuation_gensim(self): """Ensure that continued training has had a measurable effect.""" model = train_gensim(min_count=0) self.model_structural_sanity(model) vectors_ngrams_before = np.copy(model.wv.vectors_ngrams) word = 'human' old_vector = model.wv.get_vector(word).tolist() model.train(list_corpus, total_examples=len(list_corpus), epochs=model.epochs) vectors_ngrams_after = np.copy(model.wv.vectors_ngrams) self.assertFalse(np.allclose(vectors_ngrams_before, vectors_ngrams_after)) new_vector = model.wv.get_vector(word).tolist() self.assertNotEqual(old_vector, new_vector) self.model_structural_sanity(model) def test_save_load_gensim(self): """Test that serialization works end-to-end. Not crashing is a success.""" # # This is a workaround for a problem with temporary files on AppVeyor: # # - https://bugs.python.org/issue14243 (problem discussion) # - https://github.com/dropbox/pyannotate/pull/48/files (workaround source code) # model_name = 'test_ft_saveload_native.model' with temporary_file(model_name): train_gensim().save(model_name) model = FT_gensim.load(model_name) self.model_structural_sanity(model) model.train(list_corpus, total_examples=len(list_corpus), epochs=model.epochs) model.save(model_name) self.model_structural_sanity(model) def test_save_load_native(self): """Test that serialization works end-to-end. Not crashing is a success.""" model_name = 'test_ft_saveload_fb.model' with temporary_file(model_name): load_native().save(model_name) model = FT_gensim.load(model_name) self.model_structural_sanity(model) model.train(list_corpus, total_examples=len(list_corpus), epochs=model.epochs) model.save(model_name) self.model_structural_sanity(model) def test_load_native_pretrained(self): model = gensim.models.fasttext.load_facebook_model(datapath('toy-model-pretrained.bin')) actual = model.wv['monarchist'] expected = np.array([0.76222, 1.0669, 0.7055, -0.090969, -0.53508]) self.assertTrue(np.allclose(expected, actual, atol=10e-4)) self.model_structural_sanity(model) def test_load_native_vectors(self): cap_path = datapath("crime-and-punishment.bin") fbkv = gensim.models.fasttext.load_facebook_vectors(cap_path) self.assertFalse('landlord' in fbkv.key_to_index) self.assertTrue('landlady' in fbkv.key_to_index) oov_vector = fbkv['landlord'] iv_vector = fbkv['landlady'] self.assertFalse(np.allclose(oov_vector, iv_vector)) def test_no_ngrams(self): model = gensim.models.fasttext.load_facebook_model(datapath('crime-and-punishment.bin')) v1 = model.wv[''] origin = np.zeros(v1.shape, v1.dtype) self.assertTrue(np.allclose(v1, origin)) self.model_structural_sanity(model) def _train_model_with_pretrained_vectors(): """Generate toy-model-pretrained.bin for use in test_load_native_pretrained. Requires https://github.com/facebookresearch/fastText/tree/master/python to be installed. """ import fastText training_text = datapath('toy-data.txt') pretrained_file = datapath('pretrained.vec') model = fastText.train_unsupervised( training_text, bucket=100, model='skipgram', dim=5, pretrainedVectors=pretrained_file ) model.save_model(datapath('toy-model-pretrained.bin'))
NativeTrainingContinuationTest
python
wandb__wandb
wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/fsevents2.py
{ "start": 2138, "end": 4313 }
class ____(Thread): """ Low level FSEvents client. """ def __init__(self, path): Thread.__init__(self) self._queue = queue.Queue() self._run_loop = None if isinstance(path, bytes): path = path.decode('utf-8') self._path = unicodedata.normalize('NFC', path) context = None latency = 1.0 self._stream_ref = FSEventStreamCreate( kCFAllocatorDefault, self._callback, context, [self._path], kFSEventStreamEventIdSinceNow, latency, kFSEventStreamCreateFlagNoDefer | kFSEventStreamCreateFlagFileEvents) if self._stream_ref is None: raise IOError("FSEvents. Could not create stream.") def run(self): pool = AppKit.NSAutoreleasePool.alloc().init() self._run_loop = CFRunLoopGetCurrent() FSEventStreamScheduleWithRunLoop( self._stream_ref, self._run_loop, kCFRunLoopDefaultMode) if not FSEventStreamStart(self._stream_ref): FSEventStreamInvalidate(self._stream_ref) FSEventStreamRelease(self._stream_ref) raise IOError("FSEvents. Could not start stream.") CFRunLoopRun() FSEventStreamStop(self._stream_ref) FSEventStreamInvalidate(self._stream_ref) FSEventStreamRelease(self._stream_ref) del pool # Make sure waiting thread is notified self._queue.put(None) def stop(self): if self._run_loop is not None: CFRunLoopStop(self._run_loop) def _callback(self, streamRef, clientCallBackInfo, numEvents, eventPaths, eventFlags, eventIDs): events = [NativeEvent(path, flags, _id) for path, flags, _id in zip(eventPaths, eventFlags, eventIDs)] logger.debug("FSEvents callback. Got %d events:" % numEvents) for e in events: logger.debug(e) self._queue.put(events) def read_events(self): """ Returns a list or one or more events, or None if there are no more events to be read. """ if not self.is_alive(): return None return self._queue.get()
FSEventsQueue
python
Farama-Foundation__Gymnasium
docs/tutorials/gymnasium_basics/implementing_custom_wrappers.py
{ "start": 2786, "end": 3971 }
class ____(ActionWrapper): def __init__(self, env, disc_to_cont): super().__init__(env) self.disc_to_cont = disc_to_cont self.action_space = Discrete(len(disc_to_cont)) def action(self, act): return self.disc_to_cont[act] env = gym.make("LunarLanderContinuous-v3") # print(env.action_space) # Box(-1.0, 1.0, (2,), float32) wrapped_env = DiscreteActions( env, [np.array([1, 0]), np.array([-1, 0]), np.array([0, 1]), np.array([0, -1])] ) # print(wrapped_env.action_space) # Discrete(4) # %% # Inheriting from :class:`gymnasium.RewardWrapper` # ------------------------------------------------ # Reward wrappers are used to transform the reward that is returned by an environment. # As for the previous wrappers, you need to specify that transformation by implementing the # :meth:`gymnasium.RewardWrapper.reward` method. # # Let us look at an example: Sometimes (especially when we do not have control over the reward # because it is intrinsic), we want to clip the reward to a range to gain some numerical stability. # To do that, we could, for instance, implement the following wrapper: from typing import SupportsFloat
DiscreteActions
python
Textualize__textual
src/textual/canvas.py
{ "start": 1176, "end": 2248 }
class ____(Primitive): """A horizontal line.""" origin: Offset length: int color: Color line_type: CanvasLineType = "thin" def render(self, canvas: Canvas) -> None: x, y = self.origin if y < 0 or y > canvas.height - 1: return box = canvas.box box_line = box[y] line_type_index = _LINE_TYPE_INDEX[self.line_type] _combine_quads = combine_quads right = x + self.length - 1 x_range = canvas.x_range(x, x + self.length) if x in x_range: box_line[x] = _combine_quads(box_line[x], (0, line_type_index, 0, 0)) if right in x_range: box_line[right] = _combine_quads( box_line[right], (0, 0, 0, line_type_index) ) line_quad = (0, line_type_index, 0, line_type_index) for box_x in canvas.x_range(x + 1, x + self.length - 1): box_line[box_x] = _combine_quads(box_line[box_x], line_quad) canvas.spans[y].append(_Span(x, x + self.length, self.color)) @dataclass
HorizontalLine
python
run-llama__llama_index
llama-index-integrations/vector_stores/llama-index-vector-stores-nile/llama_index/vector_stores/nile/base.py
{ "start": 937, "end": 21625 }
class ____(BasePydanticVectorStore): """ Nile (Multi-tenant Postgres) Vector Store. Examples: `pip install llama-index-vector-stores-nile` ```python from llama_index.vector_stores.nile import NileVectorStore # Create NileVectorStore instance vector_store = NileVectorStore.from_params( service_url="postgresql://user:password@us-west-2.db.thenile.dev:5432/niledb", table_name="test_table", tenant_aware=True, num_dimensions=1536 ) ``` """ stores_text: bool = True flat_metadata: bool = False service_url: str table_name: str num_dimensions: int tenant_aware: bool _sync_conn: Any = PrivateAttr() _async_conn: Any = PrivateAttr() def _create_clients(self) -> None: self._sync_conn = psycopg.connect(self.service_url) self._async_conn = psycopg.connect(self.service_url) def _create_tables(self) -> None: _logger.info( f"Creating tables for {self.table_name} with {self.num_dimensions} dimensions" ) with self._sync_conn.cursor() as cursor: if self.tenant_aware: query = sql.SQL( """ CREATE TABLE IF NOT EXISTS {table_name} (id UUID DEFAULT (gen_random_uuid()), tenant_id UUID, embedding VECTOR({num_dimensions}), content TEXT, metadata JSONB) """ ).format( table_name=sql.Identifier(self.table_name), num_dimensions=sql.Literal(self.num_dimensions), ) cursor.execute(query) else: query = sql.SQL( """ CREATE TABLE IF NOT EXISTS {table_name} (id UUID DEFAULT (gen_random_uuid()), embedding VECTOR({num_dimensions}), content TEXT, metadata JSONB) """ ).format( table_name=sql.Identifier(self.table_name), num_dimensions=sql.Literal(self.num_dimensions), ) cursor.execute(query) self._sync_conn.commit() def __init__( self, service_url: str, table_name: str, tenant_aware: bool = False, num_dimensions: int = DEFAULT_EMBEDDING_DIM, ) -> None: super().__init__( service_url=service_url, table_name=table_name, num_dimensions=num_dimensions, tenant_aware=tenant_aware, ) self._create_clients() self._create_tables() @classmethod def class_name(cls) -> str: return "NileVectorStore" @property def client(self) -> Any: return self._sync_conn async def close(self) -> None: self._sync_conn.close() await self._async_conn.close() @classmethod def from_params( cls, service_url: str, table_name: str, tenant_aware: bool = False, num_dimensions: int = DEFAULT_EMBEDDING_DIM, ) -> "NileVectorStore": return cls( service_url=service_url, table_name=table_name, tenant_aware=tenant_aware, num_dimensions=num_dimensions, ) # We extract tenant_id from the node metadata. def _node_to_row(self, node: BaseNode) -> Any: metadata = node_to_metadata_dict( node, remove_text=True, flat_metadata=self.flat_metadata, ) tenant_id = node.metadata.get("tenant_id", None) return [ tenant_id, metadata, node.get_content(metadata_mode=MetadataMode.NONE), node.embedding, ] def _insert_row(self, cursor: Any, row: Any) -> str: _logger.debug(f"Inserting row into {self.table_name} with tenant_id {row[0]}") if self.tenant_aware: if row[0] is None: # Nile would fail the insert itself, but this saves the DB call and easier to test raise ValueError("tenant_id cannot be None if tenant_aware is True") query = sql.SQL( """ INSERT INTO {} (tenant_id, metadata, content, embedding) VALUES (%(tenant_id)s, %(metadata)s, %(content)s, %(embedding)s) returning id """ ).format(sql.Identifier(self.table_name)) cursor.execute( query, { "tenant_id": row[0], "metadata": json.dumps(row[1]), "content": row[2], "embedding": row[3], }, ) else: query = sql.SQL( """ INSERT INTO {} (metadata, content, embedding) VALUES (%(metadata)s, %(content)s, %(embedding)s) returning id """ ).format(sql.Identifier(self.table_name)) cursor.execute( query, { "metadata": json.dumps(row[0]), "content": row[1], "embedding": row[2], }, ) id = cursor.fetchone()[0] self._sync_conn.commit() return id def add(self, nodes: List[BaseNode], **add_kwargs: Any) -> List[str]: rows_to_insert = [self._node_to_row(node) for node in nodes] ids = [] with self._sync_conn.cursor() as cursor: for row in rows_to_insert: # this will throw an error if tenant_id is None and tenant_aware is True, which is what we want ids.append( self._insert_row(cursor, row) ) # commit is called in _insert_row return ids async def async_add(self, nodes: List[BaseNode], **add_kwargs: Any) -> List[str]: rows_to_insert = [self._node_to_row(node) for node in nodes] ids = [] async with self._async_conn.cursor() as cursor: for row in rows_to_insert: ids.append(self._insert_row(cursor, row)) await self._async_conn.commit() return ids def _set_tenant_context(self, cursor: Any, tenant_id: Any) -> None: if self.tenant_aware: cursor.execute( sql.SQL(""" set local nile.tenant_id = {} """).format( sql.Literal(tenant_id) ) ) def _to_postgres_operator(self, operator: FilterOperator) -> str: if operator == FilterOperator.EQ: return "=" elif operator == FilterOperator.GT: return ">" elif operator == FilterOperator.LT: return "<" elif operator == FilterOperator.NE: return "!=" elif operator == FilterOperator.GTE: return ">=" elif operator == FilterOperator.LTE: return "<=" elif operator == FilterOperator.IN: return "IN" elif operator == FilterOperator.NIN: return "NOT IN" elif operator == FilterOperator.CONTAINS: return "@>" elif operator == FilterOperator.TEXT_MATCH: return "LIKE" elif operator == FilterOperator.TEXT_MATCH_INSENSITIVE: return "ILIKE" else: _logger.warning(f"Unknown operator: {operator}, fallback to '='") return "=" def _create_where_clause(self, filters: MetadataFilters) -> Tuple[sql.SQL, dict]: where_clauses = [] params = {} param_counter = 0 if filters is None: return sql.SQL(""), params _logger.debug(f"Filters: {filters}") for filter in filters.filters: param_counter += 1 param_name = f"param_{param_counter}" if isinstance(filter, MetadataFilters): raise ValueError("Nested MetadataFilters are not supported yet") if isinstance(filter, MetadataFilter): key_param = f"key_{param_counter}" params[key_param] = filter.key if filter.operator in [FilterOperator.IN, FilterOperator.NIN]: params[param_name] = filter.value where_clauses.append( sql.SQL("metadata->>%({})s {} %({})s").format( sql.Identifier(key_param), sql.SQL(self._to_postgres_operator(filter.operator)), sql.Identifier(param_name), ) ) elif filter.operator in [FilterOperator.CONTAINS]: params[param_name] = filter.value where_clauses.append( sql.SQL("metadata->%({})s @> %({})s::jsonb").format( sql.Identifier(key_param), sql.Identifier(param_name) ) ) elif ( filter.operator == FilterOperator.TEXT_MATCH or filter.operator == FilterOperator.TEXT_MATCH_INSENSITIVE ): # Safely handle text match operations params[param_name] = ( f"%{filter.value}%" # Add wildcards in parameter, not in SQL ) where_clauses.append( sql.SQL("metadata->>%({})s {} %({})s").format( sql.Identifier(key_param), sql.SQL(self._to_postgres_operator(filter.operator)), sql.Identifier(param_name), ) ) else: params[param_name] = filter.value where_clauses.append( sql.SQL("metadata->>%({})s {} %({})s").format( sql.Identifier(key_param), sql.SQL(self._to_postgres_operator(filter.operator)), sql.Identifier(param_name), ) ) _logger.debug(f"Where clauses: {where_clauses}") if len(where_clauses) == 0: return sql.SQL(""), params else: # Ensure the condition is either 'AND' or 'OR' safe_condition = "AND" if hasattr(filters, "condition") and filters.condition.upper() in [ "AND", "OR", ]: safe_condition = filters.condition.upper() return ( sql.SQL(" WHERE {}").format( sql.SQL(f" {safe_condition} ").join(where_clauses) ), params, ) def _execute_query( self, cursor: Any, query_embedding: VectorStoreQuery, tenant_id: Any = None, ivfflat_probes: Any = None, hnsw_ef_search: Any = None, ) -> List[Any]: _logger.info(f"Querying {self.table_name} with tenant_id {tenant_id}") self._set_tenant_context(cursor, tenant_id) if ivfflat_probes is not None: cursor.execute( sql.SQL("""SET ivfflat.probes = {}""").format( sql.Literal(ivfflat_probes) ) ) if hnsw_ef_search is not None: cursor.execute( sql.SQL("""SET hnsw.ef_search = {}""").format( sql.Literal(hnsw_ef_search) ) ) where_clause, where_params = self._create_where_clause(query_embedding.filters) query_params = { "query_embedding": query_embedding.query_embedding, **where_params, # Merge the where clause parameters } query = sql.SQL( """ SELECT id, metadata, content, %(query_embedding)s::vector<=>embedding as distance FROM {table_name} {where_clause} ORDER BY distance LIMIT {limit} """ ).format( table_name=sql.Identifier(self.table_name), where_clause=where_clause, limit=sql.Literal(query_embedding.similarity_top_k), ) cursor.execute(query, query_params) return cursor.fetchall() def _process_query_results(self, results: List[Any]) -> VectorStoreQueryResult: nodes = [] similarities = [] ids = [] for row in results: node = metadata_dict_to_node(row[1]) node.set_content(row[2]) nodes.append(node) similarities.append(row[3]) ids.append(row[0]) return VectorStoreQueryResult(nodes=nodes, similarities=similarities, ids=ids) # NOTE: Maybe handle tenant_id specified in filter vs. kwargs # NOTE: Add support for additional query modes def query( self, query_embedding: VectorStoreQuery, **kwargs: Any ) -> VectorStoreQueryResult: # get and validate tenant_id tenant_id = kwargs.get("tenant_id") ivfflat_probes = kwargs.get("ivfflat_probes") hnsw_ef_search = kwargs.get("hnsw_ef_search") if self.tenant_aware and tenant_id is None: raise ValueError( "tenant_id must be specified in kwargs if tenant_aware is True" ) # check query mode if query_embedding.mode != VectorStoreQueryMode.DEFAULT: raise ValueError("Only DEFAULT mode is currently supported") # query with self._sync_conn.cursor() as cursor: self._set_tenant_context(cursor, tenant_id) results = self._execute_query( cursor, query_embedding, tenant_id, ivfflat_probes, hnsw_ef_search ) self._sync_conn.commit() return self._process_query_results(results) async def aquery( self, query_embedding: VectorStoreQuery, **kwargs: Any ) -> VectorStoreQueryResult: tenant_id = kwargs.get("tenant_id") if self.tenant_aware and tenant_id is None: raise ValueError( "tenant_id must be specified in kwargs if tenant_aware is True" ) async with self._async_conn.cursor() as cursor: results = self._execute_query(cursor, query_embedding, tenant_id) await self._async_conn.commit() return self._process_query_results(results) def create_tenant(self, tenant_name: str) -> uuid.UUID: """ Create a new tenant and return the tenant_id. Parameters ---------- tenant_name (str): The name of the tenant to create. Returns ------- tenant_id (uuid.UUID): The id of the newly created tenant. """ with self._sync_conn.cursor() as cursor: cursor.execute( """ INSERT INTO tenants (name) VALUES (%(tenant_name)s) returning id """, {"tenant_name": tenant_name}, ) tenant_id = cursor.fetchone()[0] self._sync_conn.commit() return tenant_id def create_index(self, index_type: IndexType, **kwargs: Any) -> None: """ Create an index of the specified type. Run this after populating the table. We intentionally throw an error if the index already exists. Since you may want to try a different type or parameters, we recommend dropping the index first. Parameters ---------- index_type (IndexType): The type of index to create. m (optional int): The number of neighbors to consider during construction for PGVECTOR_HSNW index. ef_construction (optional int): The construction parameter for PGVECTOR_HSNW index. nlists (optional int): The number of lists for PGVECTOR_IVFFLAT index. """ _logger.info(f"Creating index of type {index_type} for {self.table_name}") if index_type == IndexType.PGVECTOR_HNSW: m = kwargs.get("m") ef_construction = kwargs.get("ef_construction") if m is None or ef_construction is None: raise ValueError( "m and ef_construction must be specified in kwargs for PGVECTOR_HSNW index" ) query = sql.SQL( """ CREATE INDEX {index_name} ON {table_name} USING hnsw (embedding vector_cosine_ops) WITH (m = {m}, ef_construction = {ef_construction}); """ ).format( table_name=sql.Identifier(self.table_name), index_name=sql.Identifier(f"{self.table_name}_embedding_idx"), m=sql.Literal(m), ef_construction=sql.Literal(ef_construction), ) with self._sync_conn.cursor() as cursor: try: cursor.execute(query) self._sync_conn.commit() except psycopg.errors.DuplicateTable: self._sync_conn.rollback() raise psycopg.errors.DuplicateTable( f"Index {self.table_name}_embedding_idx already exists" ) elif index_type == IndexType.PGVECTOR_IVFFLAT: nlists = kwargs.get("nlists") if nlists is None: raise ValueError( "nlist must be specified in kwargs for PGVECTOR_IVFFLAT index" ) query = sql.SQL( """ CREATE INDEX {index_name} ON {table_name} USING ivfflat (embedding vector_cosine_ops) WITH (lists = {nlists}); """ ).format( table_name=sql.Identifier(self.table_name), index_name=sql.Identifier(f"{self.table_name}_embedding_idx"), nlists=sql.Literal(nlists), ) with self._sync_conn.cursor() as cursor: try: cursor.execute(query) self._sync_conn.commit() except psycopg.errors.DuplicateTable: self._sync_conn.rollback() raise psycopg.errors.DuplicateTable( f"Index {self.table_name}_embedding_idx already exists" ) else: raise ValueError(f"Unknown index type: {index_type}") def drop_index(self) -> None: _logger.info(f"Dropping index for {self.table_name}") query = sql.SQL( """ DROP INDEX IF EXISTS {index_name}; """ ).format(index_name=sql.Identifier(f"{self.table_name}_embedding_idx")) with self._sync_conn.cursor() as cursor: cursor.execute(query) self._sync_conn.commit() def delete(self, ref_doc_id: str, **delete_kwargs: Any) -> None: tenant_id = delete_kwargs.get("tenant_id") _logger.info(f"Deleting document {ref_doc_id} with tenant_id {tenant_id}") if self.tenant_aware and tenant_id is None: raise ValueError( "tenant_id must be specified in delete_kwargs if tenant_aware is True" ) with self._sync_conn.cursor() as cursor: self._set_tenant_context(cursor, tenant_id) cursor.execute( sql.SQL( "DELETE FROM {} WHERE metadata->>'doc_id' = %(ref_doc_id)s" ).format(sql.Identifier(self.table_name)), {"ref_doc_id": ref_doc_id}, ) self._sync_conn.commit() async def adelete(self, ref_doc_id: str, **delete_kwargs: Any) -> None: tenant_id = delete_kwargs.get("tenant_id") _logger.info(f"Deleting document {ref_doc_id} with tenant_id {tenant_id}") if self.tenant_aware and tenant_id is None: raise ValueError( "tenant_id must be specified in delete_kwargs if tenant_aware is True" ) async with self._async_conn.cursor() as cursor: self._set_tenant_context(cursor, tenant_id) cursor.execute( sql.SQL( "DELETE FROM {} WHERE metadata->>'doc_id' = %(ref_doc_id)s" ).format(sql.Identifier(self.table_name)), {"ref_doc_id": ref_doc_id}, ) await self._async_conn.commit() # NOTE: Implement get_nodes # NOTE: Implement delete_nodes # NOTE: Implement clear
NileVectorStore
python
spyder-ide__spyder
external-deps/spyder-kernels/spyder_kernels/comms/commbase.py
{ "start": 17424, "end": 19558 }
class ____(): """Class to call the other side of the comms like a function.""" def __init__(self, name, comms_wrapper, comm_id, callback, settings): self._name = name self._comms_wrapper = comms_wrapper self._comm_id = comm_id self._settings = settings self._callback = callback def __call__(self, *args, **kwargs): """ Transmit the call to the other side of the tunnel. The args and kwargs have to be JSON-serializable or bytes. """ blocking = 'blocking' in self._settings and self._settings['blocking'] self._settings['send_reply'] = blocking or self._callback is not None # The call will be serialized with json. The bytes are sent separately. buffers = [] buffered_args = [] buffered_kwargs = [] args = list(args) for i, arg in enumerate(args): if isinstance(arg, bytes): buffers.append(arg) buffered_args.append(i) args[i] = None for name in kwargs: arg = kwargs[name] if isinstance(arg, bytes): buffers.append(arg) buffered_kwargs.append(name) kwargs[name] = None call_id = uuid.uuid4().hex call_dict = { 'call_name': self._name, 'call_id': call_id, 'settings': self._settings, 'call_args': args, 'call_kwargs': kwargs, 'buffered_args': buffered_args, 'buffered_kwargs': buffered_kwargs } if not self._comms_wrapper.is_open(self._comm_id): # Only an error if the call is blocking. if blocking: raise CommError("The comm is not connected.") logger.debug("Call to unconnected comm: %s" % self._name) return self._comms_wrapper._register_call(call_dict, self._callback) self._comms_wrapper._send_call(call_dict, self._comm_id, buffers) return self._comms_wrapper._get_call_return_value( call_dict, self._comm_id)
RemoteCall
python
PrefectHQ__prefect
tests/server/orchestration/api/test_work_queues.py
{ "start": 1963, "end": 5880 }
class ____: async def test_create_work_queue( self, session, client, ): now = datetime.now(timezone.utc) data = WorkQueueCreate(name="wq-1").model_dump(mode="json") response = await client.post("/work_queues/", json=data) assert response.status_code == status.HTTP_201_CREATED assert response.json()["name"] == "wq-1" assert response.json()["filter"] is None assert ( datetime.fromisoformat(response.json()["created"].replace("Z", "+00:00")) >= now ) assert ( datetime.fromisoformat(response.json()["updated"].replace("Z", "+00:00")) >= now ) assert response.json()["work_pool_name"] == "default-agent-pool" work_queue_id = response.json()["id"] work_queue = await models.work_queues.read_work_queue( session=session, work_queue_id=work_queue_id ) assert str(work_queue.id) == work_queue_id assert work_queue.name == "wq-1" async def test_create_work_queue_with_priority( self, client, session, work_pool, ): data = dict(name="my-wpq", priority=99) response = await client.post( "/work_queues/", json=data, ) assert response.status_code == 201 assert response.json()["priority"] == 99 work_queue_id = response.json()["id"] work_queue = await models.work_queues.read_work_queue( session=session, work_queue_id=work_queue_id ) assert work_queue.priority == 99 async def test_create_work_queue_with_no_priority_when_low_priority_set( self, client, work_pool, ): response = await client.post("/work_queues/", json=dict(name="wpq-1")) # priority 2 because the default queue exists assert response.json()["priority"] == 2 response2 = await client.post("/work_queues/", json=dict(name="wpq-2")) assert response2.json()["priority"] == 3 async def test_create_work_queue_with_no_priority_when_high_priority_set( self, client, session, work_pool, ): response = await client.post( "/work_queues/", json=dict(name="wpq-1", priority=99) ) assert response.json()["priority"] == 99 work_queue_id = response.json()["id"] response2 = await client.post("/work_queues/", json=dict(name="wpq-2")) assert response2.json()["priority"] == 2 work_queue = await models.work_queues.read_work_queue( session=session, work_queue_id=work_queue_id ) assert work_queue.priority == 99 async def test_create_work_queue_raises_error_on_existing_name( self, client, work_queue ): data = WorkQueueCreate( name=work_queue.name, ).model_dump(mode="json") response = await client.post("/work_queues/", json=data) response = await client.post("/work_queues/", json=data) assert response.status_code == status.HTTP_409_CONFLICT @pytest.mark.parametrize( "name", [ "work/queue", r"work%queue", ], ) async def test_create_work_queue_with_invalid_characters_fails(self, client, name): response = await client.post("/work_queues/", json=dict(name=name)) assert response.status_code == status.HTTP_422_UNPROCESSABLE_ENTITY assert b"String should match pattern" in response.content async def test_create_work_queue_initially_is_not_ready(self, client): response = await client.post("/work_queues/", json=dict(name=str(uuid.uuid4()))) assert response.status_code == status.HTTP_201_CREATED assert "status" in response.json() assert response.json()["status"] == "NOT_READY"
TestCreateWorkQueue
python
pytorch__pytorch
torch/ao/quantization/pt2e/_numeric_debugger.py
{ "start": 8412, "end": 12088 }
class ____: handle: int actual_node_name: str actual_module_stack: str ref_node_name: str ref_module_stack: str results: Sequence[QuantizationComparisonResult] def _module_stack_to_str(module_stack: object) -> str: """Simplifies the stack from ("mod", "mod.foo", "mod.foo.0", "mod.foo.0.linear") to "mod.foo.0.linear" """ if not isinstance(module_stack, dict): return str(module_stack) module_values_list = list(module_stack.values()) if len(module_values_list) > 0: owning_module = module_values_list[-1][0] return str(owning_module) else: return str(module_stack) def extract_results_from_loggers( model: GraphModule, ) -> dict[int, tuple[str | None, object, list[object]]]: """For a given model, extract the tensors stats and related information for each debug handle. The reason we have a list of object, instead of Tensor is because the output of node may not be a Tensor, it could be (nested) list, tuple or dict as well. Returns: A dict is keyed by the debug_handle id and the values are a list of object recorded in loggers """ # Results maps debug handle to a tensor list for each model being compared. handles: dict[int, tuple[str | None, object, list[object]]] = {} for _name, module in model.named_children(): if isinstance(module, OutputLogger) and len(module.stats) > 0: handles[module.debug_handle] = ( module.node_name, module.nn_module_stack, module.stats, ) return handles def compare_results( ref_results: dict[int, tuple[str | None, object, list[torch.Tensor]]], actual_results: dict[int, tuple[str | None, object, list[torch.Tensor]]], ) -> dict[int, NodeAccuracySummary]: """Given two dict mapping from `debug_handle_id` (int) to list of tensors return a map from `debug_handle_id` to `NodeAccuracySummary` that contains comparison information like SQNR, MSE etc. Args: ref_results (Dict[int, Tuple[str, object, List[torch.Tensor]]]): reference results for each debug_handle_id actual_results (Dict[int, Tuple[str, object, List[torch.Tensor]]]): actual results for each debug_handle_id Returns: Dict[int, NodeAccuracySummary] """ comparisons = {} for debug_handle, (ref_name, ref_stack, ref_stats) in ref_results.items(): if debug_handle not in actual_results: log.debug( "Cannot compare for handle %s because it wasn't found in the transformed model", debug_handle, ) continue actual_name, actual_stack, actual_stats = actual_results[debug_handle] try: results = [ QuantizationComparisonResult(actual=a, ref=b) for a, b in zip(actual_stats, ref_stats) ] except Exception as e: # Add extra information for an exception from QuantizationComparisonResult # if the shapes didn't match, to include the handle and the node names. raise ValueError( f"For numeric_debug_handle={debug_handle} from ref node {ref_name} and actual node {actual_name}" ) from e comparisons[debug_handle] = NodeAccuracySummary( handle=debug_handle, actual_node_name=actual_name or "", actual_module_stack=_module_stack_to_str(actual_stack), ref_node_name=ref_name or "", ref_module_stack=_module_stack_to_str(ref_stack), results=results, ) return comparisons
NodeAccuracySummary
python
django__django
tests/apps/two_configs_one_default_app/apps.py
{ "start": 131, "end": 208 }
class ____(AppConfig): name = "apps.two_configs_one_default_app"
TwoConfigAlt
python
wandb__wandb
wandb/sdk/artifacts/_generated/input_types.py
{ "start": 4888, "end": 5134 }
class ____(GQLInput): artifact_id: GQLId = Field(alias="artifactID") artifact_portfolio_id: GQLId = Field(alias="artifactPortfolioID") client_mutation_id: Optional[str] = Field(alias="clientMutationId", default=None)
UnlinkArtifactInput
python
huggingface__transformers
tests/models/byt5/test_tokenization_byt5.py
{ "start": 822, "end": 12615 }
class ____(TokenizerTesterMixin, unittest.TestCase): tokenizer_class = ByT5Tokenizer from_pretrained_id = "google/byt5-small" test_rust_tokenizer = False @classmethod def setUpClass(cls): super().setUpClass() tokenizer = ByT5Tokenizer() tokenizer.save_pretrained(cls.tmpdirname) @cached_property def t5_base_tokenizer(self): return ByT5Tokenizer.from_pretrained("google/byt5-small") @classmethod def get_tokenizer(cls, pretrained_name=None, **kwargs) -> ByT5Tokenizer: pretrained_name = pretrained_name or cls.tmpdirname return cls.tokenizer_class.from_pretrained(pretrained_name, **kwargs) def get_clean_sequence(self, tokenizer, with_prefix_space=False, max_length=20, min_length=5) -> tuple[str, list]: # XXX The default common tokenizer tests assume that every ID is decodable on its own. # This assumption is invalid for ByT5 because single bytes might not be # valid utf-8 (byte 128 for instance). # Here we're overriding the smallest possible method to provide # a clean sequence without making the same assumption. toks = [] for i in range(len(tokenizer)): try: tok = tokenizer.decode([i], clean_up_tokenization_spaces=False) except UnicodeDecodeError: pass toks.append((i, tok)) toks = list(filter(lambda t: re.match(r"^[ a-zA-Z]+$", t[1]), toks)) toks = list(filter(lambda t: [t[0]] == tokenizer.encode(t[1], add_special_tokens=False), toks)) if max_length is not None and len(toks) > max_length: toks = toks[:max_length] if min_length is not None and len(toks) < min_length and len(toks) > 0: while len(toks) < min_length: toks = toks + toks # toks_str = [t[1] for t in toks] toks_ids = [t[0] for t in toks] # Ensure consistency output_txt = tokenizer.decode(toks_ids, clean_up_tokenization_spaces=False) if " " not in output_txt and len(toks_ids) > 1: output_txt = ( tokenizer.decode([toks_ids[0]], clean_up_tokenization_spaces=False) + " " + tokenizer.decode(toks_ids[1:], clean_up_tokenization_spaces=False) ) if with_prefix_space: output_txt = " " + output_txt output_ids = tokenizer.encode(output_txt, add_special_tokens=False) return output_txt, output_ids def test_eos_treatment(self): tokenizer = self.t5_base_tokenizer batch_with_eos_added = tokenizer(["hi</s>", "I went to the gym</s>", "</s>"]) batch_without_eos_added = tokenizer(["hi", "I went to the gym", ""]) self.assertListEqual(batch_with_eos_added["input_ids"], batch_without_eos_added["input_ids"]) def test_multibytes_char(self): tokenizer = self.t5_base_tokenizer src_text = "Unicode €." encoded = tokenizer(src_text) encoded_ids = [88, 113, 108, 102, 114, 103, 104, 35, 229, 133, 175, 49, 1] self.assertEqual(encoded["input_ids"], encoded_ids) # decoding decoded = tokenizer.decode(encoded_ids) self.assertEqual(decoded, "Unicode €.</s>") encoded = tokenizer("e è é ê ë") encoded_ids = [104, 35, 198, 171, 35, 198, 172, 35, 198, 173, 35, 198, 174, 1] self.assertEqual(encoded["input_ids"], encoded_ids) # decoding decoded = tokenizer.decode(encoded_ids) self.assertEqual(decoded, "e è é ê ë</s>") # encode/decode, but with `encode` instead of `__call__` self.assertEqual(tokenizer.decode(tokenizer.encode("e è é ê ë")), "e è é ê ë</s>") def test_prepare_batch_integration(self): tokenizer = self.t5_base_tokenizer src_text = ["A long paragraph for summarization.", "Another paragraph for summarization."] expected_src_tokens = [68, 35, 111, 114, 113, 106, 35, 115, 100, 117, 100, 106, 117, 100, 115, 107, 35, 105, 114, 117, 35, 118, 120, 112, 112, 100, 117, 108, 125, 100, 119, 108, 114, 113, 49, 1, 0] # fmt: skip batch = tokenizer(src_text, padding=True, return_tensors="pt") self.assertIsInstance(batch, BatchEncoding) result = list(batch.input_ids.numpy()[0]) self.assertListEqual(expected_src_tokens, result) self.assertEqual((2, 37), batch.input_ids.shape) self.assertEqual((2, 37), batch.attention_mask.shape) def test_empty_target_text(self): tokenizer = self.t5_base_tokenizer src_text = ["A long paragraph for summarization.", "Another paragraph for summarization."] batch = tokenizer(src_text, padding=True, return_tensors="pt") # check if input_ids are returned and no decoder_input_ids self.assertIn("input_ids", batch) self.assertIn("attention_mask", batch) self.assertNotIn("decoder_input_ids", batch) self.assertNotIn("decoder_attention_mask", batch) def test_max_length_integration(self): tokenizer = self.t5_base_tokenizer tgt_text = [ "Summary of the text.", "Another summary.", ] targets = tokenizer( text_target=tgt_text, max_length=32, padding="max_length", truncation=True, return_tensors="pt" ) self.assertEqual(32, targets["input_ids"].shape[1]) def test_eos_in_input(self): tokenizer = self.t5_base_tokenizer src_text = ["A long paragraph for summarization. </s>"] tgt_text = ["Summary of the text. </s>"] expected_src_tokens = [68, 35, 111, 114, 113, 106, 35, 115, 100, 117, 100, 106, 117, 100, 115, 107, 35, 105, 114, 117, 35, 118, 120, 112, 112, 100, 117, 108, 125, 100, 119, 108, 114, 113, 49, 35, 1] # fmt: skip expected_tgt_tokens = [86, 120, 112, 112, 100, 117, 124, 35, 114, 105, 35, 119, 107, 104, 35, 119, 104, 123, 119, 49, 35, 1] # fmt: skip batch = tokenizer(src_text, text_target=tgt_text) self.assertEqual(expected_src_tokens, batch["input_ids"][0]) self.assertEqual(expected_tgt_tokens, batch["labels"][0]) # cannot use default save_and_load_tokenizer test method because tokenizer has no vocab def test_save_and_load_tokenizer(self): # safety check on max_len default value so we are sure the test works tokenizers = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f"{tokenizer.__class__.__name__}"): self.assertNotEqual(tokenizer.model_max_length, 42) # Now let's start the test tokenizers = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f"{tokenizer.__class__.__name__}"): # Isolate this from the other tests because we save additional tokens/etc tmpdirname = tempfile.mkdtemp() sample_text = " He is very happy, UNwant\u00e9d,running" before_tokens = tokenizer.encode(sample_text, add_special_tokens=False) tokenizer.save_pretrained(tmpdirname) after_tokenizer = tokenizer.__class__.from_pretrained(tmpdirname) after_tokens = after_tokenizer.encode(sample_text, add_special_tokens=False) self.assertListEqual(before_tokens, after_tokens) shutil.rmtree(tmpdirname) tokenizers = self.get_tokenizers(model_max_length=42) for tokenizer in tokenizers: with self.subTest(f"{tokenizer.__class__.__name__}"): # Isolate this from the other tests because we save additional tokens/etc tmpdirname = tempfile.mkdtemp() sample_text = " He is very happy, UNwant\u00e9d,running" tokenizer.add_tokens(["bim", "bambam"]) extra_special_tokens = tokenizer.extra_special_tokens extra_special_tokens.append("new_extra_special_token") tokenizer.add_special_tokens( {"extra_special_tokens": extra_special_tokens}, replace_extra_special_tokens=False ) before_tokens = tokenizer.encode(sample_text, add_special_tokens=False) tokenizer.save_pretrained(tmpdirname) after_tokenizer = tokenizer.__class__.from_pretrained(tmpdirname) after_tokens = after_tokenizer.encode(sample_text, add_special_tokens=False) self.assertListEqual(before_tokens, after_tokens) self.assertIn("new_extra_special_token", after_tokenizer.extra_special_tokens) self.assertEqual(after_tokenizer.model_max_length, 42) tokenizer = tokenizer.__class__.from_pretrained(tmpdirname, model_max_length=43) self.assertEqual(tokenizer.model_max_length, 43) shutil.rmtree(tmpdirname) def test_decode_single_bytes(self): tokenizer_list = [] if self.test_rust_tokenizer: tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer())) for tokenizer_class, tokenizer_utils in tokenizer_list: with tempfile.TemporaryDirectory() as tmp_dir: tokenizer_utils.save_pretrained(tmp_dir) tokenizer = tokenizer_class.from_pretrained(tmp_dir) self.assertTrue(tokenizer.decode([255]) == "") @unittest.skip(reason="ByT5Tokenizer does not have a vocabulary") def test_get_vocab(self): pass @unittest.skip(reason="inputs cannot be pretokenized as ids depend on whole input string") def test_pretokenized_inputs(self): pass @unittest.skip(reason="ByT5Tokenizer does not have a vocabulary") def test_conversion_reversible(self): pass def test_convert_tokens_to_string_format(self): # The default common tokenizer tests uses invalid tokens for ByT5 that can only accept one-character strings # and special added tokens as tokens tokenizers = self.get_tokenizers(fast=True, do_lower_case=True) for tokenizer in tokenizers: with self.subTest(f"{tokenizer.__class__.__name__}"): tokens = ["t", "h", "i", "s", " ", "i", "s", " ", "a", " ", "t", "e", "x", "t", "</s>"] string = tokenizer.convert_tokens_to_string(tokens) self.assertIsInstance(string, str) # We need a different implementation of the test of the same name defined in TokenizerTesterMixin because this tokenizer # doesn't have a vocab def test_tokenizers_common_ids_setters(self): tokenizers = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f"{tokenizer.__class__.__name__}"): attributes_list = [ "bos_token", "eos_token", "unk_token", "sep_token", "pad_token", "cls_token", "mask_token", ] token_id_to_test_setters = 0 token_to_test_setters = tokenizer.convert_ids_to_tokens( token_id_to_test_setters, skip_special_tokens=False ) for attr in attributes_list: setattr(tokenizer, attr + "_id", None) self.assertEqual(getattr(tokenizer, attr), None) self.assertEqual(getattr(tokenizer, attr + "_id"), None) setattr(tokenizer, attr + "_id", token_id_to_test_setters) self.assertEqual(getattr(tokenizer, attr), token_to_test_setters) self.assertEqual(getattr(tokenizer, attr + "_id"), token_id_to_test_setters)
ByT5TokenizationTest
python
pytest-dev__pytest
src/_pytest/_code/code.py
{ "start": 30168, "end": 44771 }
class ____: """Presenting information about failing Functions and Generators.""" # for traceback entries flow_marker: ClassVar = ">" fail_marker: ClassVar = "E" showlocals: bool = False style: TracebackStyle = "long" abspath: bool = True tbfilter: TracebackFilter = True funcargs: bool = False truncate_locals: bool = True truncate_args: bool = True chain: bool = True astcache: dict[str | Path, ast.AST] = dataclasses.field( default_factory=dict, init=False, repr=False ) def _getindent(self, source: Source) -> int: # Figure out indent for the given source. try: s = str(source.getstatement(len(source) - 1)) except KeyboardInterrupt: raise except BaseException: try: s = str(source[-1]) except KeyboardInterrupt: raise except BaseException: return 0 return 4 + (len(s) - len(s.lstrip())) def _getentrysource(self, entry: TracebackEntry) -> Source | None: source = entry.getsource(self.astcache) if source is not None: source = source.deindent() return source def repr_args(self, entry: TracebackEntry) -> ReprFuncArgs | None: if self.funcargs: args = [] for argname, argvalue in entry.frame.getargs(var=True): if self.truncate_args: str_repr = saferepr(argvalue) else: str_repr = saferepr(argvalue, maxsize=None) args.append((argname, str_repr)) return ReprFuncArgs(args) return None def get_source( self, source: Source | None, line_index: int = -1, excinfo: ExceptionInfo[BaseException] | None = None, short: bool = False, end_line_index: int | None = None, colno: int | None = None, end_colno: int | None = None, ) -> list[str]: """Return formatted and marked up source lines.""" lines = [] if source is not None and line_index < 0: line_index += len(source) if source is None or line_index >= len(source.lines) or line_index < 0: # `line_index` could still be outside `range(len(source.lines))` if # we're processing AST with pathological position attributes. source = Source("???") line_index = 0 space_prefix = " " if short: lines.append(space_prefix + source.lines[line_index].strip()) lines.extend( self.get_highlight_arrows_for_line( raw_line=source.raw_lines[line_index], line=source.lines[line_index].strip(), lineno=line_index, end_lineno=end_line_index, colno=colno, end_colno=end_colno, ) ) else: for line in source.lines[:line_index]: lines.append(space_prefix + line) lines.append(self.flow_marker + " " + source.lines[line_index]) lines.extend( self.get_highlight_arrows_for_line( raw_line=source.raw_lines[line_index], line=source.lines[line_index], lineno=line_index, end_lineno=end_line_index, colno=colno, end_colno=end_colno, ) ) for line in source.lines[line_index + 1 :]: lines.append(space_prefix + line) if excinfo is not None: indent = 4 if short else self._getindent(source) lines.extend(self.get_exconly(excinfo, indent=indent, markall=True)) return lines def get_highlight_arrows_for_line( self, line: str, raw_line: str, lineno: int | None, end_lineno: int | None, colno: int | None, end_colno: int | None, ) -> list[str]: """Return characters highlighting a source line. Example with colno and end_colno pointing to the bar expression: "foo() + bar()" returns " ^^^^^" """ if lineno != end_lineno: # Don't handle expressions that span multiple lines. return [] if colno is None or end_colno is None: # Can't do anything without column information. return [] num_stripped_chars = len(raw_line) - len(line) start_char_offset = _byte_offset_to_character_offset(raw_line, colno) end_char_offset = _byte_offset_to_character_offset(raw_line, end_colno) num_carets = end_char_offset - start_char_offset # If the highlight would span the whole line, it is redundant, don't # show it. if num_carets >= len(line.strip()): return [] highlights = " " highlights += " " * (start_char_offset - num_stripped_chars + 1) highlights += "^" * num_carets return [highlights] def get_exconly( self, excinfo: ExceptionInfo[BaseException], indent: int = 4, markall: bool = False, ) -> list[str]: lines = [] indentstr = " " * indent # Get the real exception information out. exlines = excinfo.exconly(tryshort=True).split("\n") failindent = self.fail_marker + indentstr[1:] for line in exlines: lines.append(failindent + line) if not markall: failindent = indentstr return lines def repr_locals(self, locals: Mapping[str, object]) -> ReprLocals | None: if self.showlocals: lines = [] keys = [loc for loc in locals if loc[0] != "@"] keys.sort() for name in keys: value = locals[name] if name == "__builtins__": lines.append("__builtins__ = <builtins>") else: # This formatting could all be handled by the # _repr() function, which is only reprlib.Repr in # disguise, so is very configurable. if self.truncate_locals: str_repr = saferepr(value) else: str_repr = safeformat(value) # if len(str_repr) < 70 or not isinstance(value, (list, tuple, dict)): lines.append(f"{name:<10} = {str_repr}") # else: # self._line("%-10s =\\" % (name,)) # # XXX # pprint.pprint(value, stream=self.excinfowriter) return ReprLocals(lines) return None def repr_traceback_entry( self, entry: TracebackEntry | None, excinfo: ExceptionInfo[BaseException] | None = None, ) -> ReprEntry: lines: list[str] = [] style = ( entry._repr_style if entry is not None and entry._repr_style is not None else self.style ) if style in ("short", "long") and entry is not None: source = self._getentrysource(entry) if source is None: source = Source("???") line_index = 0 end_line_index, colno, end_colno = None, None, None else: line_index = entry.relline end_line_index = entry.end_lineno_relative colno = entry.colno end_colno = entry.end_colno short = style == "short" reprargs = self.repr_args(entry) if not short else None s = self.get_source( source=source, line_index=line_index, excinfo=excinfo, short=short, end_line_index=end_line_index, colno=colno, end_colno=end_colno, ) lines.extend(s) if short: message = f"in {entry.name}" else: message = (excinfo and excinfo.typename) or "" entry_path = entry.path path = self._makepath(entry_path) reprfileloc = ReprFileLocation(path, entry.lineno + 1, message) localsrepr = self.repr_locals(entry.locals) return ReprEntry(lines, reprargs, localsrepr, reprfileloc, style) elif style == "value": if excinfo: lines.extend(str(excinfo.value).split("\n")) return ReprEntry(lines, None, None, None, style) else: if excinfo: lines.extend(self.get_exconly(excinfo, indent=4)) return ReprEntry(lines, None, None, None, style) def _makepath(self, path: Path | str) -> str: if not self.abspath and isinstance(path, Path): try: np = bestrelpath(Path.cwd(), path) except OSError: return str(path) if len(np) < len(str(path)): return np return str(path) def repr_traceback(self, excinfo: ExceptionInfo[BaseException]) -> ReprTraceback: traceback = filter_excinfo_traceback(self.tbfilter, excinfo) if isinstance(excinfo.value, RecursionError): traceback, extraline = self._truncate_recursive_traceback(traceback) else: extraline = None if not traceback: if extraline is None: extraline = "All traceback entries are hidden. Pass `--full-trace` to see hidden and internal frames." entries = [self.repr_traceback_entry(None, excinfo)] return ReprTraceback(entries, extraline, style=self.style) last = traceback[-1] if self.style == "value": entries = [self.repr_traceback_entry(last, excinfo)] return ReprTraceback(entries, None, style=self.style) entries = [ self.repr_traceback_entry(entry, excinfo if last == entry else None) for entry in traceback ] return ReprTraceback(entries, extraline, style=self.style) def _truncate_recursive_traceback( self, traceback: Traceback ) -> tuple[Traceback, str | None]: """Truncate the given recursive traceback trying to find the starting point of the recursion. The detection is done by going through each traceback entry and finding the point in which the locals of the frame are equal to the locals of a previous frame (see ``recursionindex()``). Handle the situation where the recursion process might raise an exception (for example comparing numpy arrays using equality raises a TypeError), in which case we do our best to warn the user of the error and show a limited traceback. """ try: recursionindex = traceback.recursionindex() except Exception as e: max_frames = 10 extraline: str | None = ( "!!! Recursion error detected, but an error occurred locating the origin of recursion.\n" " The following exception happened when comparing locals in the stack frame:\n" f" {type(e).__name__}: {e!s}\n" f" Displaying first and last {max_frames} stack frames out of {len(traceback)}." ) # Type ignored because adding two instances of a List subtype # currently incorrectly has type List instead of the subtype. traceback = traceback[:max_frames] + traceback[-max_frames:] # type: ignore else: if recursionindex is not None: extraline = "!!! Recursion detected (same locals & position)" traceback = traceback[: recursionindex + 1] else: extraline = None return traceback, extraline def repr_excinfo(self, excinfo: ExceptionInfo[BaseException]) -> ExceptionChainRepr: repr_chain: list[tuple[ReprTraceback, ReprFileLocation | None, str | None]] = [] e: BaseException | None = excinfo.value excinfo_: ExceptionInfo[BaseException] | None = excinfo descr = None seen: set[int] = set() while e is not None and id(e) not in seen: seen.add(id(e)) if excinfo_: # Fall back to native traceback as a temporary workaround until # full support for exception groups added to ExceptionInfo. # See https://github.com/pytest-dev/pytest/issues/9159 reprtraceback: ReprTraceback | ReprTracebackNative if isinstance(e, BaseExceptionGroup): # don't filter any sub-exceptions since they shouldn't have any internal frames traceback = filter_excinfo_traceback(self.tbfilter, excinfo) reprtraceback = ReprTracebackNative( format_exception( type(excinfo.value), excinfo.value, traceback[0]._rawentry, ) ) else: reprtraceback = self.repr_traceback(excinfo_) reprcrash = excinfo_._getreprcrash() else: # Fallback to native repr if the exception doesn't have a traceback: # ExceptionInfo objects require a full traceback to work. reprtraceback = ReprTracebackNative(format_exception(type(e), e, None)) reprcrash = None repr_chain += [(reprtraceback, reprcrash, descr)] if e.__cause__ is not None and self.chain: e = e.__cause__ excinfo_ = ExceptionInfo.from_exception(e) if e.__traceback__ else None descr = "The above exception was the direct cause of the following exception:" elif ( e.__context__ is not None and not e.__suppress_context__ and self.chain ): e = e.__context__ excinfo_ = ExceptionInfo.from_exception(e) if e.__traceback__ else None descr = "During handling of the above exception, another exception occurred:" else: e = None repr_chain.reverse() return ExceptionChainRepr(repr_chain) @dataclasses.dataclass(eq=False)
FormattedExcinfo
python
pytorch__pytorch
test/distributed/fsdp/test_fsdp_use_orig_params.py
{ "start": 33753, "end": 45553 }
class ____(FSDPTest): """Tests parameter and gradient writeback.""" class Model(nn.Module): def __init__(self, device: torch.device): super().__init__() torch.manual_seed(42) self.lin1 = nn.Linear(5, 5, bias=True, device=device) self.lin2 = nn.Linear(5, 7, bias=True, device=device) def forward(self, x: torch.Tensor) -> torch.Tensor: z = self.lin1(x) z = nn.functional.relu(z) z = self.lin2(z) return z def get_input(self, device: torch.device) -> tuple[torch.Tensor, ...]: return (torch.randn((2, 5)).to(device),) def get_loss(self, inp, out): return out.sum() @property def world_size(self): # Force a world size of 2 since the tests hard code to the FSDP # sharding strategy return 2 def _check_param_parity(self, ddp_model: DDP, fsdp_model: FSDP): with FSDP.summon_full_params(fsdp_model): for (n1, p1), (n2, p2) in zip( ddp_model.module.named_parameters(), fsdp_model.named_parameters(), ): self.assertEqual(n1, n2) torch.testing.assert_close(p1, p2) @skip_if_lt_x_gpu(2) def test_param_writeback(self): """Tests that changes to the original parameters are written back.""" self.run_subtests( { "change_first_weight": [True, False], # first vs. second `weight` "change_data": [True, False], # change `.data` vs. variable itself }, self._test_param_writeback, ) def _test_param_writeback(self, change_first_weight: bool, change_data: bool): def transform_param(param: nn.Parameter) -> nn.Parameter: return nn.Parameter(torch.ones_like(param) * 2) # Check that the writeback propagates ddp_model = DDP( TestFSDPUseOrigParamsWriteback.Model(torch.device(device_type)), device_ids=[self.rank], ) fsdp_model = FSDP( TestFSDPUseOrigParamsWriteback.Model(torch.device(device_type)), use_orig_params=True, ) ddp = ddp_model.module # for brevity fsdp = fsdp_model.module if change_first_weight: if change_data: ddp.lin1.weight.data = transform_param(ddp.lin1.weight) fsdp.lin1.weight.data = transform_param(fsdp.lin1.weight) else: ddp.lin1.weight = transform_param(ddp.lin1.weight) fsdp.lin1.weight = transform_param(fsdp.lin1.weight) else: if change_data: ddp.lin2.weight.data = transform_param(ddp.lin2.weight) fsdp.lin2.weight.data = transform_param(fsdp.lin2.weight) else: ddp.lin2.weight = transform_param(ddp.lin2.weight) fsdp.lin2.weight = transform_param(fsdp.lin2.weight) self._check_param_parity(ddp_model, fsdp_model) # triggers a writeback @skip_if_lt_x_gpu(2) def test_grad_writeback(self): """ Tests that changes to the original parameters' gradients are written back. """ self.run_subtests( { "change_first_weight_grad": [False, True], "change_data": [False, True], # change `.data` vs. variable itself "set_to_none": [False, True], }, self._test_grad_writeback, ) def _test_grad_writeback( self, change_first_weight_grad: bool, change_data: bool, set_to_none: bool, ): if change_data and set_to_none: return # not well-defined def transform_grad(param: nn.Parameter) -> nn.Parameter: return None if set_to_none else torch.ones_like(param) * 2 ddp_model = DDP( TestFSDPUseOrigParamsWriteback.Model(torch.device(device_type)), device_ids=[self.rank], ) fsdp_model = FSDP( TestFSDPUseOrigParamsWriteback.Model(torch.device(device_type)), use_orig_params=True, ) LR = 1e-2 # TODO: If we add `summon_full_params(with_grads=True)`, then replace # the following. For now, we use the optimizer step as a surrogate for # checking that gradients were written back. ddp_optim = torch.optim.Adam(ddp_model.parameters(), lr=LR) fsdp_optim = torch.optim.Adam(fsdp_model.parameters(), lr=LR) # Generate an initial gradient inp = fsdp_model.get_input(torch.device(device_type)) ddp_out = ddp_model(*inp) fsdp_out = fsdp_model(*inp) ddp_out.sum().backward() fsdp_out.sum().backward() # Change the gradient through the original parameters ddp = ddp_model.module # for brevity fsdp = fsdp_model.module if change_first_weight_grad: if change_data: ddp.lin1.weight.grad.data = transform_grad(ddp.lin1.weight) if fsdp.lin1.weight.grad is not None: fsdp.lin1.weight.grad.data = transform_grad(fsdp.lin1.weight) else: ddp.lin1.weight.grad = transform_grad(ddp.lin1.weight) fsdp.lin1.weight.grad = transform_grad(fsdp.lin1.weight) else: if change_data: ddp.lin2.weight.grad.data = transform_grad(ddp.lin2.weight) if fsdp.lin2.weight.grad is not None: fsdp.lin2.weight.grad.data = transform_grad(fsdp.lin2.weight) else: ddp.lin2.weight.grad = transform_grad(ddp.lin2.weight) fsdp.lin2.weight.grad = transform_grad(fsdp.lin2.weight) ddp_optim.step() fsdp_optim.step() self._check_param_parity(ddp_model, fsdp_model) # triggers a writeback # Intentionally do not zero the gradient to check writeback inp = fsdp_model.get_input(torch.device(device_type)) ddp_out = ddp_model(*inp) fsdp_out = fsdp_model(*inp) ddp_out.sum().backward() fsdp_out.sum().backward() ddp_optim.step() fsdp_optim.step() self._check_param_parity(ddp_model, fsdp_model) # triggers a writeback @skip_if_lt_x_gpu(2) def test_writeback_shape_mismatch(self): fsdp_model = FSDP( TestFSDPUseOrigParamsWriteback.Model(torch.device(device_type)), use_orig_params=True, ) # Check that writing back with mismatched shape errors fsdp = fsdp_model.module # for brevity assert self.rank in (0, 1), f"Expects world size of 2 but got {self.world_size}" with self.assertRaisesRegex(RuntimeError, "Cannot writeback"): # Change the gradient to a new one with 1 added to each dimension # to force a shape mismatch when writing back if self.rank == 0: # Change `lin1.weight.grad` since it exists on rank 0 lin1_weight_shape = list(fsdp.lin1.weight.shape) for dim_index in range(len(lin1_weight_shape)): lin1_weight_shape[dim_index] += 1 fsdp.lin1.weight = nn.Parameter( torch.randn( torch.Size(lin1_weight_shape), device=fsdp.lin1.weight.device ) ) fsdp.lin1.weight.grad = torch.randn( torch.Size(lin1_weight_shape), device=fsdp.lin1.weight.device ) elif self.rank == 1: # Change `lin2.weight.grad` since it exists (partially) on rank 1 lin2_weight_shape = list(fsdp.lin2.weight.shape) for dim_index in range(len(lin2_weight_shape)): lin2_weight_shape[dim_index] += 1 fsdp.lin2.weight = nn.Parameter( torch.randn( torch.Size(lin2_weight_shape), device=fsdp.lin2.weight.device ) ) fsdp.lin2.weight.grad = torch.randn( torch.Size(lin2_weight_shape), device=fsdp.lin2.weight.device ) with FSDP.summon_full_params(fsdp_model): # triggers a writeback ... @skip_if_lt_x_gpu(2) def test_writeback_between_fwd_and_bwd_for_no_reshard_raises(self): fsdp_kwargs = { "sharding_strategy": ShardingStrategy.SHARD_GRAD_OP, "auto_wrap_policy": ModuleWrapPolicy({nn.Linear}), "use_orig_params": True, } fsdp_wrapper = functools.partial(FSDP, **fsdp_kwargs) # Test changing the parameter storage to no longer be a view into the # flat parameter fsdp_model = fsdp_wrapper( TestFSDPUseOrigParamsWriteback.Model(torch.device(device_type)) ) inp = fsdp_model.get_input(torch.device(device_type)) loss = fsdp_model(*inp).sum() fsdp_model.lin1.weight.data = fsdp_model.lin1.weight.clone() assert_msg = ( "FSDP does not support changing the parameters between forward and backward" ) with self.assertRaisesRegex(AssertionError, assert_msg): loss.backward() # Test changing the parameter variable itself fsdp_model = fsdp_wrapper( TestFSDPUseOrigParamsWriteback.Model(torch.device(device_type)) ) inp = fsdp_model.get_input(torch.device(device_type)) loss = fsdp_model(*inp).sum() fsdp_model.lin1._fsdp_wrapped_module.weight = nn.Parameter( fsdp_model.lin1.weight.clone() ) with self.assertRaisesRegex(AssertionError, assert_msg): loss.backward() @skip_if_lt_x_gpu(2) def test_no_reshard_and_mixed_precision(self): """ Tests that writeback does not falsely get triggered for a few configurations (exercising the sharded view skipping logic): - Train forward -> full-precision unshard -> train forward - Train forward -> eval forward - Train forward/backward -> eval forward -> model checkpoint """ self.run_subtests( {"use_full_prec_in_eval": [False, True]}, self._test_no_reshard_and_mixed_precision, ) def _test_no_reshard_and_mixed_precision(self, use_full_prec_in_eval: bool): if use_full_prec_in_eval: os.environ[_FSDP_USE_FULL_PREC_IN_EVAL] = "1" fsdp_kwargs = { "sharding_strategy": ShardingStrategy.SHARD_GRAD_OP, "auto_wrap_policy": ModuleWrapPolicy({nn.Linear}), "mixed_precision": MixedPrecision(param_dtype=torch.float16), "use_orig_params": True, } # Train forward -> full-precision unshard -> train forward fsdp_model = FSDP( TestFSDPUseOrigParamsWriteback.Model(torch.device(device_type)), **fsdp_kwargs, ) inp = fsdp_model.get_input(torch.device(device_type)) fsdp_model(*inp) with FSDP.summon_full_params(fsdp_model): ... fsdp_model(*inp).sum() # Train forward -> eval forward fsdp_model.train() fsdp_model(*inp) fsdp_model.eval() fsdp_model(*inp) # Train forward/backward -> eval forward -> model checkpoint fsdp_model.train() fsdp_model(*inp).sum().backward() fsdp_model.eval() fsdp_model(*inp) with FSDP.state_dict_type(fsdp_model, StateDictType.SHARDED_STATE_DICT): sd = fsdp_model.state_dict() fsdp_model.load_state_dict(sd) fsdp_model(*inp).sum().backward()
TestFSDPUseOrigParamsWriteback
python
joke2k__faker
tests/providers/test_color.py
{ "start": 4017, "end": 13659 }
class ____: """Test RandomColor class""" num_samples = 1000 seed = 4761 hsv_color_pattern: Pattern = re.compile( r"hsv\(" r"(?P<h>\d|[1-9]\d|[1-3]\d{2}), " r"(?P<s>\d|[1-9]\d|100), " r"(?P<v>\d|[1-9]\d|100)\)", ) hsl_color_pattern: Pattern = re.compile( r"hsl\(" r"(?P<h>\d|[1-9]\d|[1-3]\d{2}), " r"(?P<s>\d|[1-9]\d|[1-3]\d{2}), " r"(?P<l>\d|[1-9]\d|[1-3]\d{2})\)", ) rgb_color_pattern: Pattern = re.compile( r"rgb\(" r"(?P<r>\d|[1-9]\d|[1-3]\d{2}), " r"(?P<g>\d|[1-9]\d|[1-3]\d{2}), " r"(?P<b>\d|[1-9]\d|[1-3]\d{2})\)", ) hex_color_pattern: Pattern = re.compile(r"#[0-9a-f]{6}") def setup_method(self): self.random_color = RandomColor(seed=self.seed) def test_color_format_hsv(self, num_samples): for _ in range(num_samples): hsv_color = self.random_color.generate(color_format="hsv") match = self.hsv_color_pattern.fullmatch(hsv_color) assert match groupdict = match.groupdict() assert 0 <= int(groupdict["h"]) <= 360 assert 0 <= int(groupdict["s"]) <= 100 assert 0 <= int(groupdict["v"]) <= 100 def test_color_format_hsl(self, num_samples): for _ in range(num_samples): hsl_color = self.random_color.generate(color_format="hsl") match = self.hsl_color_pattern.fullmatch(hsl_color) assert match groupdict = match.groupdict() assert 0 <= int(groupdict["h"]) <= 360 assert 0 <= int(groupdict["s"]) <= 100 assert 0 <= int(groupdict["l"]) <= 100 def test_color_format_rgb(self, num_samples): for _ in range(num_samples): rgb_color = self.random_color.generate(color_format="rgb") match = self.rgb_color_pattern.fullmatch(rgb_color) assert match groupdict = match.groupdict() assert 0 <= int(groupdict["r"]) <= 255 assert 0 <= int(groupdict["g"]) <= 255 assert 0 <= int(groupdict["b"]) <= 255 def test_color_format_hex(self, num_samples): for _ in range(num_samples): hex_color = self.random_color.generate(color_format="hex") assert self.hex_color_pattern.fullmatch(hex_color) def test_color_format_unspecified(self, num_samples): for _ in range(num_samples): color = self.random_color.generate() assert self.hex_color_pattern.fullmatch(color) def test_rgb(self, num_samples): for _ in range(num_samples): value = self.random_color.generate_rgb() assert len(value) == 3 for i in range(3): assert isinstance(value[i], int) assert 0 <= value[i] <= 255 def test_rgb_float(self, num_samples): for _ in range(num_samples): value = self.random_color.generate_rgb_float() assert len(value) == 3 for i in range(3): assert isinstance(value[i], float) assert 0 <= value[i] <= 1 def test_hsl(self, num_samples): for _ in range(num_samples): value = self.random_color.generate_hsl() assert len(value) == 3 for i in range(3): assert isinstance(value[i], int) assert 0 <= value[0] <= 360 assert 0 <= value[1] <= 100 assert 0 <= value[2] <= 100 def test_hsv(self, num_samples): for _ in range(num_samples): value = self.random_color.generate_hsl() assert len(value) == 3 for i in range(3): assert isinstance(value[i], int) assert 0 <= value[0] <= 360 assert 0 <= value[1] <= 100 assert 0 <= value[2] <= 100 def test_hue_integer(self): # HSV format is used, because whatever hue value supplied must be present in the output for hue in range(360): colors = [self.random_color.generate(hue=hue, color_format="hsv") for _ in range(10)] for color in colors: match = self.hsv_color_pattern.fullmatch(color) assert match groupdict = match.groupdict() assert int(groupdict["h"]) == hue def test_hue_float(self, num_samples): baseline_random_color = RandomColor(seed=self.seed) for _ in range(num_samples): hue_float = random.uniform(0, 360) hue_int = int(hue_float) expected = [baseline_random_color.generate(hue=hue_int) for _ in range(10)] # Using a float value between 0 and 360 should yield the same results # as using an integer rounded down from that float value for a given seed colors = [self.random_color.generate(hue=hue_float) for _ in range(10)] assert colors == expected def test_hue_word(self): expected = ["#cecece", "#ededed", "#efefef", "#bcbcbc", "#777777"] colors = [self.random_color.generate(hue="monochrome") for _ in range(5)] assert colors == expected expected = ["#ef0b31", "#f2b7ab", "#f74c55", "#a53822", "#8e3712"] colors = [self.random_color.generate(hue="red") for _ in range(5)] assert colors == expected expected = ["#f98313", "#ddb77e", "#f9c413", "#f4ce81", "#ddae71"] colors = [self.random_color.generate(hue="orange") for _ in range(5)] assert colors == expected expected = ["#dbe04e", "#efc621", "#fff65b", "#ceaf27", "#fcf9ae"] colors = [self.random_color.generate(hue="yellow") for _ in range(5)] assert colors == expected expected = ["#05876f", "#57e095", "#50ceaa", "#e4f7a0", "#698909"] colors = [self.random_color.generate(hue="green") for _ in range(5)] assert colors == expected expected = ["#2b839b", "#a4d3e8", "#3d2caa", "#3859a0", "#52349e"] colors = [self.random_color.generate(hue="blue") for _ in range(5)] assert colors == expected expected = ["#a074e8", "#6122bf", "#9f76cc", "#250570", "#3c1599"] colors = [self.random_color.generate(hue="purple") for _ in range(5)] assert colors == expected expected = ["#c605c6", "#fcc4ec", "#d979f7", "#ce108c", "#d3289d"] colors = [self.random_color.generate(hue="pink") for _ in range(5)] assert colors == expected def test_hue_tuple_beyond_limits(self, num_samples): baseline_random_color = RandomColor(seed=self.seed) expected = [baseline_random_color.generate(hue=[0, 360]) for _ in range(num_samples)] # Using a tuple with values not between 0 and 360 should yield the same results # as using a tuple with clamped values for a given seed colors = [self.random_color.generate(hue=[-100, 4500]) for _ in range(num_samples)] assert colors == expected def test_hue_tuple_inverted_values(self, num_samples): baseline_random_color = RandomColor(seed=self.seed) expected = [baseline_random_color.generate(hue=[45, 75]) for _ in range(num_samples)] # Using a tuple with inverted values should yield the same results # as using the correctly ordered tuple for a given seed colors = [self.random_color.generate(hue=[75, 45]) for _ in range(num_samples)] assert colors == expected def test_hue_invalid(self): invalid_values = [ -0.000000001, # Very slightly under the min numerical value of 0 360.000000001, # Very slightly over the max numerical value of 360 "invalid value", # Unsupported string [1, 2, 3], # List with incorrect number of elements of valid data types ["ab", 1], # List with correct number of elements with invalid data types self, # Any other garbage ] for invalid_value in invalid_values: with pytest.raises(TypeError): self.random_color.generate(hue=invalid_value) def test_luminosity_word(self): expected = ["#2b7700", "#073c8c", "#d813aa", "#01961a", "#ce840e"] colors = [self.random_color.generate(luminosity="dark") for _ in range(5)] assert colors == expected expected = ["#16b5ff", "#6266ef", "#fc4e3f", "#b2ff70", "#a30424"] colors = [self.random_color.generate(luminosity="bright") for _ in range(5)] assert colors == expected expected = ["#f276a1", "#fcec94", "#aaffe5", "#ffbd7f", "#98f9dc"] colors = [self.random_color.generate(luminosity="light") for _ in range(5)] assert colors == expected expected = ["#070603", "#99a2a3", "#10a85c", "#3f4f0c", "#004f1c"] colors = [self.random_color.generate(luminosity="random") for _ in range(5)] assert colors == expected def test_luminosity_invalid(self, num_samples): baseline_random_color = RandomColor(seed=self.seed) expected = [baseline_random_color.generate() for _ in range(num_samples)] colors = [self.random_color.generate(luminosity="invalid_value") for _ in range(num_samples)] assert colors == expected def test_bad_color_map(self): # Initial baseline using 62 as hue value self.random_color.generate(hue=62) # If we remove 62 from the yellow range, calling the previous function should fail colormap = copy.deepcopy(self.random_color.colormap) colormap["yellow"]["hue_range"] = [(47, 61)] self.random_color.colormap = colormap with pytest.raises(ValueError): self.random_color.generate(hue=62)
TestRandomColor
python
pydata__xarray
asv_bench/benchmarks/alignment.py
{ "start": 152, "end": 1221 }
class ____: def setup(self, *args, **kwargs): data = rng.standard_normal((ntime, nx, ny)) self.ds = xr.Dataset( {"temperature": (("time", "x", "y"), data)}, coords={ "time": xr.date_range("2000", periods=ntime), "x": np.arange(nx), "y": np.arange(ny), }, ) self.year = self.ds.time.dt.year self.idx = np.unique(rng.integers(low=0, high=ntime, size=ntime // 2)) self.year_subset = self.year.isel(time=self.idx) @parameterized(["join"], [("outer", "inner", "left", "right", "exact", "override")]) def time_already_aligned(self, join): xr.align(self.ds, self.year, join=join) @parameterized(["join"], [("outer", "inner", "left", "right")]) def time_not_aligned(self, join): xr.align(self.ds, self.year[-100:], join=join) @parameterized(["join"], [("outer", "inner", "left", "right")]) def time_not_aligned_random_integers(self, join): xr.align(self.ds, self.year_subset, join=join)
Align
python
bokeh__bokeh
src/bokeh/models/filters.py
{ "start": 5633, "end": 6327 }
class ____(Filter): ''' A ``GroupFilter`` represents the rows of a ``ColumnDataSource`` where the values of the column indicated by ``column_name`` match the ``group`` variable. ''' column_name = Required(String, help=""" The name of the column to perform the group filtering operation on. """) group = Required(AnyRef, help=""" The value of the column indicating the rows of data to keep. """) def __init__(self, *args, **kwargs) -> None: if len(args) == 2 and "column_name" not in kwargs and "group" not in kwargs: kwargs["column_name"] = args[0] kwargs["group"] = args[1] super().__init__(**kwargs)
GroupFilter
python
great-expectations__great_expectations
great_expectations/core/expectation_diagnostics/supporting_types.py
{ "start": 3453, "end": 3728 }
class ____(SerializableDictDot): """Captures information about a specific Metric dependency for an Expectation. Used within the ExpectationDiagnostic object.""" # noqa: E501 # FIXME CoP name: str has_question_renderer: bool @dataclass
ExpectationMetricDiagnostics
python
html5lib__html5lib-python
html5lib/html5parser.py
{ "start": 67297, "end": 73064 }
class ____(Phase): # http://www.whatwg.org/specs/web-apps/current-work/#in-table __slots__ = tuple() # helper methods def clearStackToTableContext(self): # "clear the stack back to a table context" while self.tree.openElements[-1].name not in ("table", "html"): # self.parser.parseError("unexpected-implied-end-tag-in-table", # {"name": self.tree.openElements[-1].name}) self.tree.openElements.pop() # When the current node is <html> it's an innerHTML case # processing methods def processEOF(self): if self.tree.openElements[-1].name != "html": self.parser.parseError("eof-in-table") else: assert self.parser.innerHTML # Stop parsing def processSpaceCharacters(self, token): originalPhase = self.parser.phase self.parser.phase = self.parser.phases["inTableText"] self.parser.phase.originalPhase = originalPhase self.parser.phase.processSpaceCharacters(token) def processCharacters(self, token): originalPhase = self.parser.phase self.parser.phase = self.parser.phases["inTableText"] self.parser.phase.originalPhase = originalPhase self.parser.phase.processCharacters(token) def insertText(self, token): # If we get here there must be at least one non-whitespace character # Do the table magic! self.tree.insertFromTable = True self.parser.phases["inBody"].processCharacters(token) self.tree.insertFromTable = False def startTagCaption(self, token): self.clearStackToTableContext() self.tree.activeFormattingElements.append(Marker) self.tree.insertElement(token) self.parser.phase = self.parser.phases["inCaption"] def startTagColgroup(self, token): self.clearStackToTableContext() self.tree.insertElement(token) self.parser.phase = self.parser.phases["inColumnGroup"] def startTagCol(self, token): self.startTagColgroup(impliedTagToken("colgroup", "StartTag")) return token def startTagRowGroup(self, token): self.clearStackToTableContext() self.tree.insertElement(token) self.parser.phase = self.parser.phases["inTableBody"] def startTagImplyTbody(self, token): self.startTagRowGroup(impliedTagToken("tbody", "StartTag")) return token def startTagTable(self, token): self.parser.parseError("unexpected-start-tag-implies-end-tag", {"startName": "table", "endName": "table"}) self.parser.phase.processEndTag(impliedTagToken("table")) if not self.parser.innerHTML: return token def startTagStyleScript(self, token): return self.parser.phases["inHead"].processStartTag(token) def startTagInput(self, token): if ("type" in token["data"] and token["data"]["type"].translate(asciiUpper2Lower) == "hidden"): self.parser.parseError("unexpected-hidden-input-in-table") self.tree.insertElement(token) # XXX associate with form self.tree.openElements.pop() else: self.startTagOther(token) def startTagForm(self, token): self.parser.parseError("unexpected-form-in-table") if self.tree.formPointer is None: self.tree.insertElement(token) self.tree.formPointer = self.tree.openElements[-1] self.tree.openElements.pop() def startTagOther(self, token): self.parser.parseError("unexpected-start-tag-implies-table-voodoo", {"name": token["name"]}) # Do the table magic! self.tree.insertFromTable = True self.parser.phases["inBody"].processStartTag(token) self.tree.insertFromTable = False def endTagTable(self, token): if self.tree.elementInScope("table", variant="table"): self.tree.generateImpliedEndTags() if self.tree.openElements[-1].name != "table": self.parser.parseError("end-tag-too-early-named", {"gotName": "table", "expectedName": self.tree.openElements[-1].name}) while self.tree.openElements[-1].name != "table": self.tree.openElements.pop() self.tree.openElements.pop() self.parser.resetInsertionMode() else: # innerHTML case assert self.parser.innerHTML self.parser.parseError() def endTagIgnore(self, token): self.parser.parseError("unexpected-end-tag", {"name": token["name"]}) def endTagOther(self, token): self.parser.parseError("unexpected-end-tag-implies-table-voodoo", {"name": token["name"]}) # Do the table magic! self.tree.insertFromTable = True self.parser.phases["inBody"].processEndTag(token) self.tree.insertFromTable = False startTagHandler = _utils.MethodDispatcher([ ("html", Phase.startTagHtml), ("caption", startTagCaption), ("colgroup", startTagColgroup), ("col", startTagCol), (("tbody", "tfoot", "thead"), startTagRowGroup), (("td", "th", "tr"), startTagImplyTbody), ("table", startTagTable), (("style", "script"), startTagStyleScript), ("input", startTagInput), ("form", startTagForm) ]) startTagHandler.default = startTagOther endTagHandler = _utils.MethodDispatcher([ ("table", endTagTable), (("body", "caption", "col", "colgroup", "html", "tbody", "td", "tfoot", "th", "thead", "tr"), endTagIgnore) ]) endTagHandler.default = endTagOther
InTablePhase
python
neetcode-gh__leetcode
python/0231-power-of-two.py
{ "start": 12, "end": 176 }
class ____: def isPowerOfTwo(self, n: int) -> bool: x = 1 while x < n: x *= 2 return x == n # Bit manipulation
Solution
python
huggingface__transformers
tests/models/whisper/test_feature_extraction_whisper.py
{ "start": 1453, "end": 3484 }
class ____: def __init__( self, parent, batch_size=7, min_seq_length=400, max_seq_length=2000, feature_size=10, hop_length=160, chunk_length=8, padding_value=0.0, sampling_rate=4_000, return_attention_mask=False, do_normalize=True, ): self.parent = parent self.batch_size = batch_size self.min_seq_length = min_seq_length self.max_seq_length = max_seq_length self.seq_length_diff = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) self.padding_value = padding_value self.sampling_rate = sampling_rate self.return_attention_mask = return_attention_mask self.do_normalize = do_normalize self.feature_size = feature_size self.chunk_length = chunk_length self.hop_length = hop_length def prepare_feat_extract_dict(self): return { "feature_size": self.feature_size, "hop_length": self.hop_length, "chunk_length": self.chunk_length, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def prepare_inputs_for_common(self, equal_length=False, numpify=False): def _flatten(list_of_lists): return list(itertools.chain(*list_of_lists)) if equal_length: speech_inputs = [floats_list((self.max_seq_length, self.feature_size)) for _ in range(self.batch_size)] else: # make sure that inputs increase in size speech_inputs = [ floats_list((x, self.feature_size)) for x in range(self.min_seq_length, self.max_seq_length, self.seq_length_diff) ] if numpify: speech_inputs = [np.asarray(x) for x in speech_inputs] return speech_inputs
WhisperFeatureExtractionTester
python
geekcomputers__Python
binary_search_tree.py
{ "start": 313, "end": 11266 }
class ____: """Class for BST""" def __init__(self): """Initialising a BST""" self.root = None def insert(self, val): """Creating a BST with root value as val""" # Check if tree has root with None value if self.root is None: self.root = Node(val) # Here the tree already has one root else: current = self.root while True: if val < current.info: if current.left: current = current.left else: current.left = Node(val) break elif val > current.info: if current.right: current = current.right else: current.right = Node(val) break else: break def search(self, val, to_delete=False): current = self.root prev = -1 while current: if val < current.info: prev = current current = current.left elif val > current.info: prev = current current = current.right elif current.info == val: if not to_delete: return "Match Found" return prev else: break if not to_delete: return "Not Found" # Method to delete a tree-node if it exists, else error message will be returned. def delete(self, val): prev = self.search(val, True) # Check if node exists if prev is not None: # Check if node is the Root node if prev == -1: temp = self.root.left prev2 = None while temp.right: prev2 = temp temp = temp.right if prev2 is None: self.root.left = temp.left self.root.info = temp.info else: prev2.right = None self.root.info = temp.info print("Deleted Root ", val) # Check if node is to left of its parent elif prev.left and prev.left.info == val: # Check if node is leaf node if prev.left.left is prev.left.right: prev.left = None print("Deleted Node ", val) # Check if node has child at left and None at right elif prev.left.left and prev.left.right is None: prev.left = prev.left.left print("Deleted Node ", val) # Check if node has child at right and None at left elif prev.left.left is None and prev.left.right: prev.left = prev.left.right print("Deleted Node ", val) # Here node to be deleted has 2 children elif prev.left.left and prev.left.right: temp = prev.left while temp.right is not None: prev2 = temp temp = temp.right prev2.right = None prev.left.info = temp.info print("Deleted Node ", val) else: print("Error Left") # Check if node is to right of its parent elif prev.right.info == val: flag = 0 # Check is node is a leaf node if prev.right.left is prev.right.right: prev.right = None flag = 1 print("Deleted Node ", val) # Check if node has left child at None at right if prev.right and prev.right.left and prev.right.right is None: prev.right = prev.right.left print("Deleted Node ", val) # Check if node has right child at None at left elif prev.right and prev.right.left is None and prev.right.right: prev.right = prev.right.right print("Deleted Node ", val) elif prev.right and prev.right.left and prev.right.right: temp = prev.right while temp.left is not None: prev2 = temp temp = temp.left prev2.left = None prev.right.info = temp.info print("Deleted Node ", val) else: if flag == 0: print("Error") else: print("Node doesn't exists") def __str__(self): return "Not able to print tree yet" def is_bst(node, lower_lim=None, upper_lim=None): """Function to find is a binary tree is a binary search tree.""" if lower_lim is not None and node.info < lower_lim: return False if upper_lim is not None and node.info > upper_lim: return False is_left_bst = True is_right_bst = True if node.left is not None: is_left_bst = is_bst(node.left, lower_lim, node.info) if is_left_bst and node.right is not None: is_right_bst = is_bst(node.right, node.info, upper_lim) return is_left_bst and is_right_bst def postorder(node): # L R N : Left , Right, Node if node is None: return if node.left: postorder(node.left) if node.right: postorder(node.right) print(node.info) def inorder(node): # L N R : Left, Node , Right if node is None: return if node.left: inorder(node.left) print(node.info) if node.right: inorder(node.right) def preorder(node): # N L R : Node , Left, Right if node is None: return print(node.info) if node.left: preorder(node.left) if node.right: preorder(node.right) # Levelwise def bfs(node): queue = [] if node: queue.append(node) while queue != []: temp = queue.pop(0) print(temp.info) if temp.left: queue.append(temp.left) if temp.right: queue.append(temp.right) def preorder_itr(node): # N L R : Node, Left , Right stack = [node] values = [] while stack != []: temp = stack.pop() print(temp.info) values.append(temp.info) if temp.right: stack.append(temp.right) if temp.left: stack.append(temp.left) return values def inorder_itr(node): # L N R : Left, Node, Right # 1) Create an empty stack S. # 2) Initialize current node as root # 3) Push the current node to S and set current = current->left until current is NULL # 4) If current is NULL and stack is not empty then # a) Pop the top item from stack. # b) Print the popped item, set current = popped_item->right # c) Go to step 3. # 5) If current is NULL and stack is empty then we are done. stack = [] current = node while True: if current != None: stack.append(current) # L current = current.left elif stack != []: temp = stack.pop() print(temp.info) # N current = temp.right # R else: break def postorder_itr(node): # L R N # 1. Push root to first stack. # 2. Loop while first stack is not empty # 2.1 Pop a node from first stack and push it to second stack # 2.2 Push left and right children of the popped node to first stack # 3. Print contents of second stack s1, s2 = [node], [] while s1 != []: temp = s1.pop() s2.append(temp) if temp.left: s1.append(temp.left) if temp.right: s1.append(temp.right) print(*(s2[::-1])) def bst_frm_pre(pre_list): box = Node(pre_list[0]) if len(pre_list) > 1: if len(pre_list) == 2: if pre_list[1] > pre_list[0]: box.right = Node(pre_list[1]) else: box.left = Node(pre_list[1]) else: all_less = False for i in range(1, len(pre_list)): if pre_list[i] > pre_list[0]: break else: all_less = True if i != 1: box.left = bst_frm_pre(pre_list[1:i]) if not all_less: box.right = bst_frm_pre(pre_list[i:]) return box # Function to find the lowest common ancestor of nodes with values c1 and c2. # It return value in the lowest common ancestor, -1 indicates value returned for None. # Note that both values v1 and v2 should be present in the bst. def lca(t_node, c1, c2): if c1 == c2: return c1 current = t_node while current: if c1 < current.info and c2 < current.info: current = current.left elif c1 > current.info and c2 > current.info: current = current.right else: return current.info return -1 # Function to print element vertically which lie just below the root node def vertical_middle_level(t_node): e = (t_node, 0) # 0 indicates level 0, to left we have -ve and to right +ve queue = [e] ans = [] # Do a level-order traversal and assign level-value to each node while queue != []: temp, level = queue.pop(0) if level == 0: ans.append(str(temp.info)) if temp.left: queue.append((temp.left, level - 1)) if temp.right: queue.append((temp.right, level + 1)) return " ".join(ans) def get_level(n, val): c_level = 0 while n.info != val: if val < n.info: n = n.left elif val > n.info: n = n.right c_level += 1 if n is None: return -1 return c_level def depth(node): if node is None: return 0 l_depth, r_depth = 0, 0 if node.left: l_depth = depth(node.left) if node.right: r_depth = depth(node.right) # print(node.info, l_depth, r_depth) return 1 + max(l_depth, r_depth) t = BinarySearchTree() t.insert(10) t.insert(5) t.insert(15) t.insert(3) t.insert(1) t.insert(0) t.insert(2) t.insert(7) t.insert(12) t.insert(18) t.insert(19) print(depth(t.root)) # inorder(t.root) # print() # print(t.search(5)) # t.delete(7) # t.delete(5) # t.delete(3) # t.delete(15) # inorder(t.root) # print() # t.delete(2) # t.delete(3) # t.delete(7) # t.delete(19) # t.delete(1) # inorder(t.root) # b = BinarySearchTree() # b.root = bst_frm_pre(preorder_itr(t.root)) # print(preorder_itr(b.root) == preorder_itr(t.root)) # print(lca(t.root, 3, 18)) # print(vertical_middle_level(t.root)) # print(get_level(t.root, 1))
BinarySearchTree
python
pytorch__pytorch
test/torch_np/numpy_tests/lib/test_function_base.py
{ "start": 7751, "end": 8232 }
class ____(TestCase): def test_basic(self): y1 = [0, 1, 1, 0] y2 = [0, 0, 0, 0] y3 = [1, 1, 1, 1] assert_(not np.all(y1)) assert_(np.all(y3)) assert_(not np.all(y2)) assert_(np.all(~np.array(y2))) def test_nd(self): y1 = [[0, 0, 1], [0, 1, 1], [1, 1, 1]] assert_(not np.all(y1)) assert_array_equal(np.all(y1, axis=0), [0, 0, 1]) assert_array_equal(np.all(y1, axis=1), [0, 0, 1])
TestAll