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
sympy__sympy
doc/src/_pygments/styles.py
{ "start": 634, "end": 2255 }
class ____(Style): """ Like Sphinx (which is like friendly, but a bit darker to enhance contrast on the green background) but with higher contrast colors. """ @property def _pre_style(self): # This is used instead of the default 125% so that multiline Unicode # pprint output looks good return 'line-height: 120%;' background_color = '#eeffcc' default_style = '' styles = FriendlyStyle.styles styles.update({ # These are part of the Sphinx modification to "friendly" Generic.Output: '#333', Number: '#208050', # These are adjusted from "friendly" (Comment is adjusted from # "sphinx") to have better color contrast against the background. Comment: 'italic #3c7a88', Comment.Hashbang: 'italic #3c7a88', Comment.Multiline: 'italic #3c7a88', Comment.PreprocFile: 'italic #3c7a88', Comment.Single: 'italic #3c7a88', Comment.Special: '#3a7784 bg:#fff0f0', Generic.Error: '#e60000', Generic.Inserted: '#008200', Generic.Prompt: 'bold #b75709', Name.Class: 'bold #0e7ba6', Name.Constant: '#2b79a1', Name.Entity: 'bold #c54629', Name.Namespace: 'bold #0e7ba6', Name.Variable: '#ab40cd', Text.Whitespace: '#707070', Literal.String.Interpol: 'italic #3973b7', Literal.String.Other: '#b75709', Name.Variable.Class: '#ab40cd', Name.Variable.Global: '#ab40cd', Name.Variable.Instance: '#ab40cd', Name.Variable.Magic: '#ab40cd', })
SphinxHighContrastStyle
python
pytorch__pytorch
test/package/package_a/test_module.py
{ "start": 108, "end": 309 }
class ____(torch.nn.Module): def __init__(self, script_mod): super().__init__() self.script_mod = script_mod def forward(self, x): return self.script_mod(x)
ModWithSubmod
python
ansible__ansible
lib/ansible/modules/hostname.py
{ "start": 6161, "end": 6803 }
class ____(BaseStrategy): FILE = '/etc/hostname' def get_permanent_hostname(self): if not os.path.isfile(self.FILE): return '' try: return get_file_content(self.FILE, default='', strip=True) except Exception as e: self.module.fail_json( msg="failed to read hostname: %s" % to_native(e)) def set_permanent_hostname(self, name): try: with open(self.FILE, 'w+') as f: f.write("%s\n" % name) except Exception as e: self.module.fail_json(msg="failed to update hostname: %s" % to_native(e))
FileStrategy
python
encode__django-rest-framework
rest_framework/viewsets.py
{ "start": 8878, "end": 9292 }
class ____(mixins.CreateModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, mixins.ListModelMixin, GenericViewSet): """ A viewset that provides default `create()`, `retrieve()`, `update()`, `partial_update()`, `destroy()` and `list()` actions. """ pass
ModelViewSet
python
jazzband__django-waffle
waffle/templatetags/waffle_tags.py
{ "start": 2294, "end": 2498 }
class ____(template.Node): def render(self, context): return _generate_waffle_js(context['request']) @register.tag def wafflejs(parser, token): return InlineWaffleJSNode()
InlineWaffleJSNode
python
optuna__optuna
optuna/cli.py
{ "start": 19510, "end": 21349 }
class ____(_BaseCommand): """Show a list of trials located at the Pareto front.""" def add_arguments(self, parser: ArgumentParser) -> None: parser.add_argument( "--study-name", type=str, required=True, help="The name of the study to get the best trials (trials at the Pareto front).", ) parser.add_argument( "-f", "--format", type=str, choices=("value", "json", "table", "yaml"), default="table", help="Output format.", ) parser.add_argument( "--flatten", default=False, action="store_true", help="Flatten nested columns such as params and user_attrs.", ) def take_action(self, parsed_args: Namespace) -> int: optuna_warn( "'best-trials' is an experimental CLI command. The interface can change in the " "future.", ExperimentalWarning, ) storage = _get_storage(parsed_args.storage, parsed_args.storage_class) study = optuna.load_study(storage=storage, study_name=parsed_args.study_name) best_trials = [trial.number for trial in study.best_trials] attrs = ( "number", "value" if not study._is_multi_objective() else "values", "datetime_start", "datetime_complete", "duration", "params", "user_attrs", "state", ) records, columns = _dataframe._create_records_and_aggregate_column(study, attrs) best_records = list(filter(lambda record: record[("number", "")] in best_trials, records)) print(_format_output(best_records, columns, parsed_args.format, parsed_args.flatten)) return 0
_BestTrials
python
ray-project__ray
python/ray/tune/experimental/output.py
{ "start": 27752, "end": 31013 }
class ____(TuneReporterBase): def experiment_started( self, experiment_name: str, experiment_path: str, searcher_str: str, scheduler_str: str, total_num_samples: int, tensorboard_path: Optional[str] = None, **kwargs, ): if total_num_samples > sys.maxsize: total_num_samples_str = "infinite" else: total_num_samples_str = str(total_num_samples) print( tabulate( [ ["Search algorithm", searcher_str], ["Scheduler", scheduler_str], ["Number of trials", total_num_samples_str], ], headers=["Configuration for experiment", experiment_name], tablefmt=AIR_TABULATE_TABLEFMT, ) ) super().experiment_started( experiment_name=experiment_name, experiment_path=experiment_path, searcher_str=searcher_str, scheduler_str=scheduler_str, total_num_samples=total_num_samples, tensorboard_path=tensorboard_path, **kwargs, ) def _print_heartbeat(self, trials, *sys_args, force: bool = False): if self._verbosity < self._heartbeat_threshold and not force: return heartbeat_strs, table_data = self._get_heartbeat( trials, *sys_args, force_full_output=force ) self._start_block("heartbeat") for s in heartbeat_strs: print(s) # now print the table using Tabulate more_infos = [] all_data = [] fail_header = table_data.header for sub_table in table_data.data: all_data.extend(sub_table.trial_infos) if sub_table.more_info: more_infos.append(sub_table.more_info) print( tabulate( all_data, headers=fail_header, tablefmt=AIR_TABULATE_TABLEFMT, showindex=False, ) ) if more_infos: print(", ".join(more_infos)) if not force: # Only print error table at end of training return trials_with_error = _get_trials_with_error(trials) if not trials_with_error: return self._start_block("status_errored") print(f"Number of errored trials: {len(trials_with_error)}") fail_header = ["Trial name", "# failures", "error file"] fail_table_data = [ [ str(trial), str(trial.run_metadata.num_failures) + ("" if trial.status == Trial.ERROR else "*"), trial.error_file, ] for trial in trials_with_error ] print( tabulate( fail_table_data, headers=fail_header, tablefmt=AIR_TABULATE_TABLEFMT, showindex=False, colalign=("left", "right", "left"), ) ) if any(trial.status == Trial.TERMINATED for trial in trials_with_error): print("* The trial terminated successfully after retrying.")
TuneTerminalReporter
python
apache__airflow
airflow-core/tests/unit/api_fastapi/auth/managers/test_base_auth_manager.py
{ "start": 4907, "end": 20537 }
class ____: def test_get_cli_commands_return_empty_list(self, auth_manager): assert auth_manager.get_cli_commands() == [] def test_get_fastapi_app_return_none(self, auth_manager): assert auth_manager.get_fastapi_app() is None def test_refresh_user_default_returns_none(self, auth_manager): assert auth_manager.refresh_user(user=BaseAuthManagerUserTest(name="test")) is None def test_get_url_logout_return_none(self, auth_manager): assert auth_manager.get_url_logout() is None def test_get_extra_menu_items_return_empty_list(self, auth_manager): assert auth_manager.get_extra_menu_items(user=BaseAuthManagerUserTest(name="test")) == [] def test_get_db_manager_return_none(self, auth_manager): assert auth_manager.get_db_manager() is None def test_is_authorized_team(self, auth_manager): with pytest.raises( NotImplementedError, match="The auth manager you are using is not compatible with multi-team" ): auth_manager.is_authorized_team(method="GET", user=BaseAuthManagerUserTest(name="test")) @patch.object(EmptyAuthManager, "filter_authorized_menu_items") def test_get_authorized_menu_items(self, mock_filter_authorized_menu_items, auth_manager): user = BaseAuthManagerUserTest(name="test") mock_filter_authorized_menu_items.return_value = [] results = auth_manager.get_authorized_menu_items(user=user) mock_filter_authorized_menu_items.assert_called_once_with(list(MenuItem), user=user) assert results == [] @patch( "airflow.api_fastapi.auth.managers.base_auth_manager.BaseAuthManager._get_token_validator", autospec=True, ) @patch.object(EmptyAuthManager, "deserialize_user") @pytest.mark.asyncio async def test_get_user_from_token(self, mock_deserialize_user, mock__get_token_validator, auth_manager): token = "token" payload = {} user = BaseAuthManagerUserTest(name="test") signer = AsyncMock(spec=JWTValidator) signer.avalidated_claims.return_value = payload mock__get_token_validator.return_value = signer mock_deserialize_user.return_value = user result = await auth_manager.get_user_from_token(token) mock_deserialize_user.assert_called_once_with(payload) signer.avalidated_claims.assert_called_once_with(token) assert result == user @patch( "airflow.api_fastapi.auth.managers.base_auth_manager.BaseAuthManager._get_token_validator", autospec=True, ) @patch.object(EmptyAuthManager, "deserialize_user") @pytest.mark.asyncio async def test_get_user_from_token_invalid_token_payload( self, mock_deserialize_user, mock__get_token_validator, auth_manager ): token = "token" payload = {} signer = AsyncMock(spec=JWTValidator) signer.avalidated_claims.return_value = payload mock__get_token_validator.return_value = signer mock_deserialize_user.side_effect = ValueError("Some error deserializing the user") with pytest.raises(InvalidTokenError, match="Some error deserializing the user"): await auth_manager.get_user_from_token(token) mock_deserialize_user.assert_called_once_with(payload) signer.avalidated_claims.assert_called_once_with(token) @patch("airflow.api_fastapi.auth.managers.base_auth_manager.JWTGenerator", autospec=True) @patch.object(EmptyAuthManager, "serialize_user") def test_generate_jwt_token(self, mock_serialize_user, mock_jwt_generator, auth_manager): token = "token" serialized_user = "serialized_user" signer = Mock(spec=JWTGenerator) signer.generate.return_value = token mock_jwt_generator.return_value = signer mock_serialize_user.return_value = {"sub": serialized_user} user = BaseAuthManagerUserTest(name="test") result = auth_manager.generate_jwt(user) mock_serialize_user.assert_called_once_with(user) signer.generate.assert_called_once_with({"sub": serialized_user}) assert result == token @pytest.mark.parametrize( ("return_values", "expected"), [ ([False, False], False), ([True, False], False), ([True, True], True), ], ) @patch.object(EmptyAuthManager, "is_authorized_connection") def test_batch_is_authorized_connection( self, mock_is_authorized_connection, auth_manager, return_values, expected ): mock_is_authorized_connection.side_effect = return_values result = auth_manager.batch_is_authorized_connection( [ {"method": "GET", "details": ConnectionDetails(conn_id="conn1")}, {"method": "GET", "details": ConnectionDetails(conn_id="conn2")}, ], user=Mock(), ) assert result == expected @pytest.mark.parametrize( ("return_values", "expected"), [ ([False, False], False), ([True, False], False), ([True, True], True), ], ) @patch.object(EmptyAuthManager, "is_authorized_dag") def test_batch_is_authorized_dag(self, mock_is_authorized_dag, auth_manager, return_values, expected): mock_is_authorized_dag.side_effect = return_values result = auth_manager.batch_is_authorized_dag( [ {"method": "GET", "details": DagDetails(id="dag1")}, {"method": "GET", "details": DagDetails(id="dag2")}, ], user=Mock(), ) assert result == expected @pytest.mark.parametrize( ("return_values", "expected"), [ ([False, False], False), ([True, False], False), ([True, True], True), ], ) @patch.object(EmptyAuthManager, "is_authorized_pool") def test_batch_is_authorized_pool(self, mock_is_authorized_pool, auth_manager, return_values, expected): mock_is_authorized_pool.side_effect = return_values result = auth_manager.batch_is_authorized_pool( [ {"method": "GET", "details": PoolDetails(name="pool1")}, {"method": "GET", "details": PoolDetails(name="pool2")}, ], user=Mock(), ) assert result == expected @pytest.mark.parametrize( ("return_values", "expected"), [ ([False, False], False), ([True, False], False), ([True, True], True), ], ) @patch.object(EmptyAuthManager, "is_authorized_variable") def test_batch_is_authorized_variable( self, mock_is_authorized_variable, auth_manager, return_values, expected ): mock_is_authorized_variable.side_effect = return_values result = auth_manager.batch_is_authorized_variable( [ {"method": "GET", "details": VariableDetails(key="var1")}, {"method": "GET", "details": VariableDetails(key="var2")}, ], user=Mock(), ) assert result == expected @pytest.mark.parametrize( ("access_per_dag", "access_per_team", "rows", "expected"), [ # Without teams # No access to any dag ( {}, {}, [("dag1", None), ("dag2", None)], set(), ), # Access to specific dags ( {"dag1": True}, {}, [("dag1", None), ("dag2", None)], {"dag1"}, ), # With teams # No access to any dag ( {}, {}, [("dag1", "team1"), ("dag2", "team2")], set(), ), # Access to a specific team ( {}, {"team1": True}, [("dag1", "team1"), ("dag2", "team1"), ("dag3", "team2")], {"dag1", "dag2"}, ), ], ) def test_get_authorized_dag_ids( self, auth_manager, access_per_dag: dict, access_per_team: dict, rows: list, expected: set ): def side_effect_func( *, method: ResourceMethod, user: BaseAuthManagerUserTest, access_entity: DagAccessEntity | None = None, details: DagDetails | None = None, ): if not details: return False return access_per_dag.get(details.id, False) or access_per_team.get(details.team_name, False) auth_manager.is_authorized_dag = MagicMock(side_effect=side_effect_func) user = Mock() session = Mock() session.execute.return_value.all.return_value = rows result = auth_manager.get_authorized_dag_ids(user=user, session=session) assert result == expected @pytest.mark.parametrize( ("access_per_connection", "access_per_team", "rows", "expected"), [ # Without teams # No access to any connection ( {}, {}, [("conn1", None), ("conn2", None)], set(), ), # Access to specific connections ( {"conn1": True}, {}, [("conn1", None), ("conn2", None)], {"conn1"}, ), # With teams # No access to any connection ( {}, {}, [("conn1", "team1"), ("conn2", "team2")], set(), ), # Access to a specific team ( {}, {"team1": True}, [("conn1", "team1"), ("conn2", "team1"), ("conn3", "team2")], {"conn1", "conn2"}, ), ], ) def test_get_authorized_connections( self, auth_manager, access_per_connection: dict, access_per_team: dict, rows: list, expected: set ): def side_effect_func( *, method: ResourceMethod, user: BaseAuthManagerUserTest, details: ConnectionDetails | None = None, ): if not details: return False return access_per_connection.get(details.conn_id, False) or access_per_team.get( details.team_name, False ) auth_manager.is_authorized_connection = MagicMock(side_effect=side_effect_func) user = Mock() session = Mock() session.execute.return_value.all.return_value = rows result = auth_manager.get_authorized_connections(user=user, session=session) assert result == expected @pytest.mark.parametrize( ("access_per_team", "rows", "expected"), [ # No access to any team ( {}, [("1", "team1"), ("2", "team2")], set(), ), # Access to specific teams ( {"team1": True}, [("1", "team1"), ("2", "team2")], {"team1"}, ), ], ) def test_get_authorized_teams(self, auth_manager, access_per_team: dict, rows: list, expected: set): def side_effect_func( *, method: ResourceMethod, user: BaseAuthManagerUserTest, details: TeamDetails | None = None, ): if not details: return False return access_per_team.get(details.name, False) auth_manager.is_authorized_team = MagicMock(side_effect=side_effect_func) user = Mock() session = Mock() session.execute.return_value.all.return_value = rows result = auth_manager.get_authorized_teams(user=user, session=session) assert result == expected @pytest.mark.parametrize( ("access_per_variable", "access_per_team", "rows", "expected"), [ # Without teams # No access to any variable ( {}, {}, [("var1", None), ("var2", None)], set(), ), # Access to specific variables ( {"var1": True}, {}, [("var1", None), ("var2", None)], {"var1"}, ), # With teams # No access to any variable ( {}, {}, [("var1", "team1"), ("var2", "team2")], set(), ), # Access to a specific team ( {}, {"team1": True}, [("var1", "team1"), ("var2", "team1"), ("var3", "team2")], {"var1", "var2"}, ), ], ) def test_get_authorized_variables( self, auth_manager, access_per_variable: dict, access_per_team: dict, rows: list, expected: set ): def side_effect_func( *, method: ResourceMethod, user: BaseAuthManagerUserTest, details: VariableDetails | None = None, ): if not details: return False return access_per_variable.get(details.key, False) or access_per_team.get( details.team_name, False ) auth_manager.is_authorized_variable = MagicMock(side_effect=side_effect_func) user = Mock() session = Mock() session.execute.return_value.all.return_value = rows result = auth_manager.get_authorized_variables(user=user, session=session) assert result == expected @pytest.mark.parametrize( ("access_per_pool", "access_per_team", "rows", "expected"), [ # Without teams # No access to any pool ( {}, {}, [("pool1", None), ("pool2", None)], set(), ), # Access to specific pools ( {"pool1": True}, {}, [("pool1", None), ("pool2", None)], {"pool1"}, ), # With teams # No access to any pool ( {}, {}, [("pool1", "team1"), ("pool2", "team2")], set(), ), # Access to a specific team ( {}, {"team1": True}, [("pool1", "team1"), ("pool2", "team1"), ("pool3", "team2")], {"pool1", "pool2"}, ), ], ) def test_get_authorized_pools( self, auth_manager, access_per_pool: dict, access_per_team: dict, rows: list, expected: set ): def side_effect_func( *, method: ResourceMethod, user: BaseAuthManagerUserTest, details: PoolDetails | None = None, ): if not details: return False return access_per_pool.get(details.name, False) or access_per_team.get(details.team_name, False) auth_manager.is_authorized_pool = MagicMock(side_effect=side_effect_func) user = Mock() session = Mock() session.execute.return_value.all.return_value = rows result = auth_manager.get_authorized_pools(user=user, session=session) assert result == expected
TestBaseAuthManager
python
ray-project__ray
rllib/policy/tests/test_policy_state_swapping.py
{ "start": 337, "end": 4676 }
class ____(unittest.TestCase): """Tests, whether Policies' states can be swapped out via their state on a GPU.""" @classmethod def setUpClass(cls) -> None: ray.init() @classmethod def tearDownClass(cls) -> None: ray.shutdown() def test_policy_swap_gpu(self): config = ( APPOConfig().api_stack( enable_rl_module_and_learner=False, enable_env_runner_and_connector_v2=False, ) # Use a single GPU for this test. .resources(num_gpus=1) ) obs_space = gym.spaces.Box(-1.0, 1.0, (4,), dtype=np.float32) dummy_obs = obs_space.sample() act_space = gym.spaces.Discrete(100) num_policies = 2 capacity = 1 cls = get_tf_eager_cls_if_necessary(APPOTorchPolicy, config) # Create empty, swappable-policies PolicyMap. policy_map = PolicyMap(capacity=capacity, policy_states_are_swappable=True) # Create and add some TF2 policies. for i in range(num_policies): config.training(lr=(i + 1) * 0.01) policy = cls( observation_space=obs_space, action_space=act_space, config=config.to_dict(), ) policy_map[f"pol{i}"] = policy # Create a dummy batch with all 1.0s in it (instead of zeros), so we have a # better chance of changing our weights during an update. dummy_batch_ones = tree.map_structure( lambda s: np.ones_like(s), policy_map["pol0"]._dummy_batch, ) dummy_batch_twos = tree.map_structure( lambda s: np.full_like(s, 2.0), policy_map["pol0"]._dummy_batch, ) logits = { pid: p.compute_single_action(dummy_obs)[2]["action_dist_inputs"] for pid, p in policy_map.items() } # Make sure policies output different deterministic actions. Otherwise, # this test would not work. check(logits["pol0"], logits["pol1"], atol=0.0000001, false=True) # Test proper policy state swapping. for i in range(50): pid = f"pol{i % num_policies}" print(i) pol = policy_map[pid] # Make sure config has been changed properly. self.assertTrue(pol.config["lr"] == ((i % num_policies) + 1) * 0.01) # After accessing `pid`, assume it's the most recently accessed # item now. self.assertTrue(policy_map._deque[-1] == pid) self.assertTrue(len(policy_map._deque) == capacity) self.assertTrue(len(policy_map.cache) == capacity) self.assertTrue(pid in policy_map.cache) # Actually compute one action to trigger tracing operations of # the graph. These may be performed lazily by the DL framework. check( pol.compute_single_action(dummy_obs)[2]["action_dist_inputs"], logits[pid], ) # Test, whether training (on the GPU) will affect the state swapping. for i in range(num_policies): pid = f"pol{i % num_policies}" pol = policy_map[pid] if i == 0: pol.learn_on_batch(dummy_batch_ones) else: assert i == 1 pol.learn_on_batch(dummy_batch_twos) # Make sure, we really changed the NN during training and update our # actions dict. old_logits = logits[pid] logits[pid] = pol.compute_single_action(dummy_obs)[2]["action_dist_inputs"] check(logits[pid], old_logits, atol=0.0000001, false=True) # Make sure policies output different deterministic actions. Otherwise, # this test would not work. check(logits["pol0"], logits["pol1"], atol=0.0000001, false=True) # Once more, test proper policy state swapping. for i in range(50): pid = f"pol{i % num_policies}" pol = policy_map[pid] check( pol.compute_single_action(dummy_obs)[2]["action_dist_inputs"], logits[pid], ) if __name__ == "__main__": import sys import pytest sys.exit(pytest.main(["-v", __file__]))
TestPolicyStateSwapping
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/utils/eks_test_constants.py
{ "start": 4191, "end": 4417 }
class ____: """All possible inputs for creating an AWS Fargate profile.""" REQUIRED: list[tuple[str, Any]] = [POD_EXECUTION_ROLE_ARN, SELECTORS] OPTIONAL: list[tuple[str, Any]] = [SUBNETS, TAGS]
FargateProfileInputs
python
ray-project__ray
rllib/models/preprocessors.py
{ "start": 5973, "end": 7083 }
class ____(Preprocessor): """One-hot preprocessor for Discrete and MultiDiscrete spaces. .. testcode:: :skipif: True self.transform(Discrete(3).sample()) .. testoutput:: np.array([0.0, 1.0, 0.0]) .. testcode:: :skipif: True self.transform(MultiDiscrete([2, 3]).sample()) .. testoutput:: np.array([0.0, 1.0, 0.0, 0.0, 1.0]) """ @override(Preprocessor) def _init_shape(self, obs_space: gym.Space, options: dict) -> List[int]: if isinstance(obs_space, gym.spaces.Discrete): return (self._obs_space.n,) else: return (np.sum(self._obs_space.nvec),) @override(Preprocessor) def transform(self, observation: TensorType) -> np.ndarray: self.check_shape(observation) return gym.spaces.utils.flatten(self._obs_space, observation).astype(np.float32) @override(Preprocessor) def write(self, observation: TensorType, array: np.ndarray, offset: int) -> None: array[offset : offset + self.size] = self.transform(observation) @OldAPIStack
OneHotPreprocessor
python
django__django
tests/field_deconstruction/tests.py
{ "start": 217, "end": 30248 }
class ____(SimpleTestCase): """ Tests the deconstruct() method on all core fields. """ def test_name(self): """ Tests the outputting of the correct name if assigned one. """ # First try using a "normal" field field = models.CharField(max_length=65) name, path, args, kwargs = field.deconstruct() self.assertIsNone(name) field.set_attributes_from_name("is_awesome_test") name, path, args, kwargs = field.deconstruct() self.assertEqual(name, "is_awesome_test") # Now try with a ForeignKey field = models.ForeignKey("some_fake.ModelName", models.CASCADE) name, path, args, kwargs = field.deconstruct() self.assertIsNone(name) field.set_attributes_from_name("author") name, path, args, kwargs = field.deconstruct() self.assertEqual(name, "author") def test_db_tablespace(self): field = models.Field() _, _, args, kwargs = field.deconstruct() self.assertEqual(args, []) self.assertEqual(kwargs, {}) # With a DEFAULT_DB_TABLESPACE. with self.settings(DEFAULT_DB_TABLESPACE="foo"): _, _, args, kwargs = field.deconstruct() self.assertEqual(args, []) self.assertEqual(kwargs, {}) # With a db_tablespace. field = models.Field(db_tablespace="foo") _, _, args, kwargs = field.deconstruct() self.assertEqual(args, []) self.assertEqual(kwargs, {"db_tablespace": "foo"}) # With a db_tablespace equal to DEFAULT_DB_TABLESPACE. with self.settings(DEFAULT_DB_TABLESPACE="foo"): _, _, args, kwargs = field.deconstruct() self.assertEqual(args, []) self.assertEqual(kwargs, {"db_tablespace": "foo"}) def test_auto_field(self): field = models.AutoField(primary_key=True) field.set_attributes_from_name("id") name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.AutoField") self.assertEqual(args, []) self.assertEqual(kwargs, {"primary_key": True}) def test_big_integer_field(self): field = models.BigIntegerField() name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.BigIntegerField") self.assertEqual(args, []) self.assertEqual(kwargs, {}) def test_boolean_field(self): field = models.BooleanField() name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.BooleanField") self.assertEqual(args, []) self.assertEqual(kwargs, {}) field = models.BooleanField(default=True) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.BooleanField") self.assertEqual(args, []) self.assertEqual(kwargs, {"default": True}) def test_char_field(self): field = models.CharField(max_length=65) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.CharField") self.assertEqual(args, []) self.assertEqual(kwargs, {"max_length": 65}) field = models.CharField(max_length=65, null=True, blank=True) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.CharField") self.assertEqual(args, []) self.assertEqual(kwargs, {"max_length": 65, "null": True, "blank": True}) def test_char_field_choices(self): field = models.CharField(max_length=1, choices=(("A", "One"), ("B", "Two"))) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.CharField") self.assertEqual(args, []) self.assertEqual( kwargs, {"choices": [("A", "One"), ("B", "Two")], "max_length": 1} ) def test_choices_iterator(self): field = models.IntegerField(choices=((i, str(i)) for i in range(3))) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.IntegerField") self.assertEqual(args, []) self.assertEqual(kwargs, {"choices": [(0, "0"), (1, "1"), (2, "2")]}) def test_choices_iterable(self): # Pass an iterable (but not an iterator) to choices. field = models.IntegerField(choices="012345") name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.IntegerField") self.assertEqual(args, []) self.assertEqual(kwargs, {"choices": normalize_choices("012345")}) def test_choices_callable(self): def get_choices(): return [(i, str(i)) for i in range(3)] field = models.IntegerField(choices=get_choices) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.IntegerField") self.assertEqual(args, []) self.assertEqual(kwargs, {"choices": get_choices}) def test_csi_field(self): field = models.CommaSeparatedIntegerField(max_length=100) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.CommaSeparatedIntegerField") self.assertEqual(args, []) self.assertEqual(kwargs, {"max_length": 100}) def test_date_field(self): field = models.DateField() name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.DateField") self.assertEqual(args, []) self.assertEqual(kwargs, {}) field = models.DateField(auto_now=True) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.DateField") self.assertEqual(args, []) self.assertEqual(kwargs, {"auto_now": True}) def test_datetime_field(self): field = models.DateTimeField() name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.DateTimeField") self.assertEqual(args, []) self.assertEqual(kwargs, {}) field = models.DateTimeField(auto_now_add=True) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.DateTimeField") self.assertEqual(args, []) self.assertEqual(kwargs, {"auto_now_add": True}) # Bug #21785 field = models.DateTimeField(auto_now=True, auto_now_add=True) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.DateTimeField") self.assertEqual(args, []) self.assertEqual(kwargs, {"auto_now_add": True, "auto_now": True}) def test_decimal_field(self): field = models.DecimalField(max_digits=5, decimal_places=2) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.DecimalField") self.assertEqual(args, []) self.assertEqual(kwargs, {"max_digits": 5, "decimal_places": 2}) def test_decimal_field_0_decimal_places(self): """ A DecimalField with decimal_places=0 should work (#22272). """ field = models.DecimalField(max_digits=5, decimal_places=0) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.DecimalField") self.assertEqual(args, []) self.assertEqual(kwargs, {"max_digits": 5, "decimal_places": 0}) def test_email_field(self): field = models.EmailField() name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.EmailField") self.assertEqual(args, []) self.assertEqual(kwargs, {"max_length": 254}) field = models.EmailField(max_length=255) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.EmailField") self.assertEqual(args, []) self.assertEqual(kwargs, {"max_length": 255}) def test_file_field(self): field = models.FileField(upload_to="foo/bar") name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.FileField") self.assertEqual(args, []) self.assertEqual(kwargs, {"upload_to": "foo/bar"}) # Test max_length field = models.FileField(upload_to="foo/bar", max_length=200) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.FileField") self.assertEqual(args, []) self.assertEqual(kwargs, {"upload_to": "foo/bar", "max_length": 200}) def test_file_path_field(self): field = models.FilePathField(match=r".*\.txt$") name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.FilePathField") self.assertEqual(args, []) self.assertEqual(kwargs, {"match": r".*\.txt$"}) field = models.FilePathField(recursive=True, allow_folders=True, max_length=123) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.FilePathField") self.assertEqual(args, []) self.assertEqual( kwargs, {"recursive": True, "allow_folders": True, "max_length": 123} ) def test_float_field(self): field = models.FloatField() name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.FloatField") self.assertEqual(args, []) self.assertEqual(kwargs, {}) def test_foreign_key(self): # Test basic pointing from django.contrib.auth.models import Permission field = models.ForeignKey("auth.Permission", models.CASCADE) field.remote_field.model = Permission field.remote_field.field_name = "id" name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.ForeignKey") self.assertEqual(args, []) self.assertEqual(kwargs, {"to": "auth.permission", "on_delete": models.CASCADE}) self.assertFalse(hasattr(kwargs["to"], "setting_name")) # Test swap detection for swappable model field = models.ForeignKey("auth.User", models.CASCADE) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.ForeignKey") self.assertEqual(args, []) self.assertEqual(kwargs, {"to": "auth.user", "on_delete": models.CASCADE}) self.assertEqual(kwargs["to"].setting_name, "AUTH_USER_MODEL") # Swap detection for lowercase swappable model. field = models.ForeignKey("auth.user", models.CASCADE) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.ForeignKey") self.assertEqual(args, []) self.assertEqual(kwargs, {"to": "auth.user", "on_delete": models.CASCADE}) self.assertEqual(kwargs["to"].setting_name, "AUTH_USER_MODEL") # Test nonexistent (for now) model field = models.ForeignKey("something.Else", models.CASCADE) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.ForeignKey") self.assertEqual(args, []) self.assertEqual(kwargs, {"to": "something.else", "on_delete": models.CASCADE}) # Test on_delete field = models.ForeignKey("auth.User", models.SET_NULL) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.ForeignKey") self.assertEqual(args, []) self.assertEqual(kwargs, {"to": "auth.user", "on_delete": models.SET_NULL}) # Test to_field preservation field = models.ForeignKey("auth.Permission", models.CASCADE, to_field="foobar") name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.ForeignKey") self.assertEqual(args, []) self.assertEqual( kwargs, { "to": "auth.permission", "to_field": "foobar", "on_delete": models.CASCADE, }, ) # Test related_name preservation field = models.ForeignKey( "auth.Permission", models.CASCADE, related_name="foobar" ) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.ForeignKey") self.assertEqual(args, []) self.assertEqual( kwargs, { "to": "auth.permission", "related_name": "foobar", "on_delete": models.CASCADE, }, ) # Test related_query_name field = models.ForeignKey( "auth.Permission", models.CASCADE, related_query_name="foobar" ) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.ForeignKey") self.assertEqual(args, []) self.assertEqual( kwargs, { "to": "auth.permission", "related_query_name": "foobar", "on_delete": models.CASCADE, }, ) # Test limit_choices_to field = models.ForeignKey( "auth.Permission", models.CASCADE, limit_choices_to={"foo": "bar"} ) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.ForeignKey") self.assertEqual(args, []) self.assertEqual( kwargs, { "to": "auth.permission", "limit_choices_to": {"foo": "bar"}, "on_delete": models.CASCADE, }, ) # Test unique field = models.ForeignKey("auth.Permission", models.CASCADE, unique=True) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.ForeignKey") self.assertEqual(args, []) self.assertEqual( kwargs, {"to": "auth.permission", "unique": True, "on_delete": models.CASCADE}, ) @override_settings(AUTH_USER_MODEL="auth.Permission") def test_foreign_key_swapped(self): with isolate_lru_cache(apps.get_swappable_settings_name): # It doesn't matter that we swapped out user for permission; # there's no validation. We just want to check the setting stuff # works. field = models.ForeignKey("auth.Permission", models.CASCADE) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.ForeignKey") self.assertEqual(args, []) self.assertEqual(kwargs, {"to": "auth.permission", "on_delete": models.CASCADE}) self.assertEqual(kwargs["to"].setting_name, "AUTH_USER_MODEL") # Model names are case-insensitive. with isolate_lru_cache(apps.get_swappable_settings_name): # It doesn't matter that we swapped out user for permission; # there's no validation. We just want to check the setting stuff # works. field = models.ForeignKey("auth.permission", models.CASCADE) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.ForeignKey") self.assertEqual(args, []) self.assertEqual(kwargs, {"to": "auth.permission", "on_delete": models.CASCADE}) self.assertEqual(kwargs["to"].setting_name, "AUTH_USER_MODEL") def test_one_to_one(self): # Test basic pointing from django.contrib.auth.models import Permission field = models.OneToOneField("auth.Permission", models.CASCADE) field.remote_field.model = Permission field.remote_field.field_name = "id" name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.OneToOneField") self.assertEqual(args, []) self.assertEqual(kwargs, {"to": "auth.permission", "on_delete": models.CASCADE}) self.assertFalse(hasattr(kwargs["to"], "setting_name")) # Test swap detection for swappable model field = models.OneToOneField("auth.User", models.CASCADE) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.OneToOneField") self.assertEqual(args, []) self.assertEqual(kwargs, {"to": "auth.user", "on_delete": models.CASCADE}) self.assertEqual(kwargs["to"].setting_name, "AUTH_USER_MODEL") # Test nonexistent (for now) model field = models.OneToOneField("something.Else", models.CASCADE) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.OneToOneField") self.assertEqual(args, []) self.assertEqual(kwargs, {"to": "something.else", "on_delete": models.CASCADE}) # Test on_delete field = models.OneToOneField("auth.User", models.SET_NULL) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.OneToOneField") self.assertEqual(args, []) self.assertEqual(kwargs, {"to": "auth.user", "on_delete": models.SET_NULL}) # Test to_field field = models.OneToOneField( "auth.Permission", models.CASCADE, to_field="foobar" ) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.OneToOneField") self.assertEqual(args, []) self.assertEqual( kwargs, { "to": "auth.permission", "to_field": "foobar", "on_delete": models.CASCADE, }, ) # Test related_name field = models.OneToOneField( "auth.Permission", models.CASCADE, related_name="foobar" ) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.OneToOneField") self.assertEqual(args, []) self.assertEqual( kwargs, { "to": "auth.permission", "related_name": "foobar", "on_delete": models.CASCADE, }, ) # Test related_query_name field = models.OneToOneField( "auth.Permission", models.CASCADE, related_query_name="foobar" ) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.OneToOneField") self.assertEqual(args, []) self.assertEqual( kwargs, { "to": "auth.permission", "related_query_name": "foobar", "on_delete": models.CASCADE, }, ) # Test limit_choices_to field = models.OneToOneField( "auth.Permission", models.CASCADE, limit_choices_to={"foo": "bar"} ) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.OneToOneField") self.assertEqual(args, []) self.assertEqual( kwargs, { "to": "auth.permission", "limit_choices_to": {"foo": "bar"}, "on_delete": models.CASCADE, }, ) # Test unique field = models.OneToOneField("auth.Permission", models.CASCADE, unique=True) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.OneToOneField") self.assertEqual(args, []) self.assertEqual(kwargs, {"to": "auth.permission", "on_delete": models.CASCADE}) def test_image_field(self): field = models.ImageField( upload_to="foo/barness", width_field="width", height_field="height" ) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.ImageField") self.assertEqual(args, []) self.assertEqual( kwargs, { "upload_to": "foo/barness", "width_field": "width", "height_field": "height", }, ) def test_integer_field(self): field = models.IntegerField() name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.IntegerField") self.assertEqual(args, []) self.assertEqual(kwargs, {}) def test_ip_address_field(self): field = models.IPAddressField() name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.IPAddressField") self.assertEqual(args, []) self.assertEqual(kwargs, {}) def test_generic_ip_address_field(self): field = models.GenericIPAddressField() name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.GenericIPAddressField") self.assertEqual(args, []) self.assertEqual(kwargs, {}) field = models.GenericIPAddressField(protocol="IPv6") name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.GenericIPAddressField") self.assertEqual(args, []) self.assertEqual(kwargs, {"protocol": "IPv6"}) def test_many_to_many_field(self): # Test normal field = models.ManyToManyField("auth.Permission") name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.ManyToManyField") self.assertEqual(args, []) self.assertEqual(kwargs, {"to": "auth.permission"}) self.assertFalse(hasattr(kwargs["to"], "setting_name")) # Test swappable field = models.ManyToManyField("auth.User") name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.ManyToManyField") self.assertEqual(args, []) self.assertEqual(kwargs, {"to": "auth.user"}) self.assertEqual(kwargs["to"].setting_name, "AUTH_USER_MODEL") # Test through field = models.ManyToManyField("auth.Permission", through="auth.Group") name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.ManyToManyField") self.assertEqual(args, []) self.assertEqual(kwargs, {"to": "auth.permission", "through": "auth.Group"}) # Test through_fields field = models.ManyToManyField( "auth.Permission", through="auth.Group", through_fields=("foo", "permissions"), ) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.ManyToManyField") self.assertEqual(args, []) self.assertEqual( kwargs, { "to": "auth.permission", "through": "auth.Group", "through_fields": ("foo", "permissions"), }, ) # Test custom db_table field = models.ManyToManyField("auth.Permission", db_table="custom_table") name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.ManyToManyField") self.assertEqual(args, []) self.assertEqual(kwargs, {"to": "auth.permission", "db_table": "custom_table"}) # Test related_name field = models.ManyToManyField("auth.Permission", related_name="custom_table") name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.ManyToManyField") self.assertEqual(args, []) self.assertEqual( kwargs, {"to": "auth.permission", "related_name": "custom_table"} ) # Test related_query_name field = models.ManyToManyField("auth.Permission", related_query_name="foobar") name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.ManyToManyField") self.assertEqual(args, []) self.assertEqual( kwargs, {"to": "auth.permission", "related_query_name": "foobar"} ) # Test limit_choices_to field = models.ManyToManyField( "auth.Permission", limit_choices_to={"foo": "bar"} ) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.ManyToManyField") self.assertEqual(args, []) self.assertEqual( kwargs, {"to": "auth.permission", "limit_choices_to": {"foo": "bar"}} ) @override_settings(AUTH_USER_MODEL="auth.Permission") def test_many_to_many_field_swapped(self): with isolate_lru_cache(apps.get_swappable_settings_name): # It doesn't matter that we swapped out user for permission; # there's no validation. We just want to check the setting stuff # works. field = models.ManyToManyField("auth.Permission") name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.ManyToManyField") self.assertEqual(args, []) self.assertEqual(kwargs, {"to": "auth.permission"}) self.assertEqual(kwargs["to"].setting_name, "AUTH_USER_MODEL") def test_many_to_many_field_related_name(self): class MyModel(models.Model): flag = models.BooleanField(default=True) m2m = models.ManyToManyField("self") m2m_related_name = models.ManyToManyField( "self", related_query_name="custom_query_name", limit_choices_to={"flag": True}, ) name, path, args, kwargs = MyModel.m2m.field.deconstruct() self.assertEqual(path, "django.db.models.ManyToManyField") self.assertEqual(args, []) # deconstruct() should not include attributes which were not passed to # the field during initialization. self.assertEqual(kwargs, {"to": "field_deconstruction.mymodel"}) # Passed attributes. name, path, args, kwargs = MyModel.m2m_related_name.field.deconstruct() self.assertEqual(path, "django.db.models.ManyToManyField") self.assertEqual(args, []) self.assertEqual( kwargs, { "to": "field_deconstruction.mymodel", "related_query_name": "custom_query_name", "limit_choices_to": {"flag": True}, }, ) def test_positive_integer_field(self): field = models.PositiveIntegerField() name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.PositiveIntegerField") self.assertEqual(args, []) self.assertEqual(kwargs, {}) def test_positive_small_integer_field(self): field = models.PositiveSmallIntegerField() name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.PositiveSmallIntegerField") self.assertEqual(args, []) self.assertEqual(kwargs, {}) def test_positive_big_integer_field(self): field = models.PositiveBigIntegerField() name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.PositiveBigIntegerField") self.assertEqual(args, []) self.assertEqual(kwargs, {}) def test_slug_field(self): field = models.SlugField() name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.SlugField") self.assertEqual(args, []) self.assertEqual(kwargs, {}) field = models.SlugField(db_index=False, max_length=231) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.SlugField") self.assertEqual(args, []) self.assertEqual(kwargs, {"db_index": False, "max_length": 231}) def test_small_integer_field(self): field = models.SmallIntegerField() name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.SmallIntegerField") self.assertEqual(args, []) self.assertEqual(kwargs, {}) def test_text_field(self): field = models.TextField() name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.TextField") self.assertEqual(args, []) self.assertEqual(kwargs, {}) def test_time_field(self): field = models.TimeField() name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.TimeField") self.assertEqual(args, []) self.assertEqual(kwargs, {}) field = models.TimeField(auto_now=True) name, path, args, kwargs = field.deconstruct() self.assertEqual(args, []) self.assertEqual(kwargs, {"auto_now": True}) field = models.TimeField(auto_now_add=True) name, path, args, kwargs = field.deconstruct() self.assertEqual(args, []) self.assertEqual(kwargs, {"auto_now_add": True}) def test_url_field(self): field = models.URLField() name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.URLField") self.assertEqual(args, []) self.assertEqual(kwargs, {}) field = models.URLField(max_length=231) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.URLField") self.assertEqual(args, []) self.assertEqual(kwargs, {"max_length": 231}) def test_binary_field(self): field = models.BinaryField() name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.BinaryField") self.assertEqual(args, []) self.assertEqual(kwargs, {}) field = models.BinaryField(editable=True) name, path, args, kwargs = field.deconstruct() self.assertEqual(args, []) self.assertEqual(kwargs, {"editable": True})
FieldDeconstructionTests
python
getsentry__sentry
tests/sentry/ratelimits/utils/test_above_rate_limit_check.py
{ "start": 413, "end": 3674 }
class ____(TestCase): group = RateLimitConfig().group def test_above_rate_limit_check(self) -> None: with freeze_time("2000-01-01"): expected_reset_time = int(time() + 100) return_val = above_rate_limit_check( "foo", RateLimit(limit=10, window=100), "request_uid", self.group ) assert return_val == RateLimitMeta( rate_limit_type=RateLimitType.NOT_LIMITED, current=1, limit=10, window=100, group=self.group, reset_time=expected_reset_time, remaining=9, concurrent_limit=settings.SENTRY_CONCURRENT_RATE_LIMIT_DEFAULT, concurrent_requests=1, ) for i in range(10): return_val = above_rate_limit_check( "foo", RateLimit(limit=10, window=100), f"request_uid{i}", self.group ) assert return_val == RateLimitMeta( rate_limit_type=RateLimitType.FIXED_WINDOW, current=11, limit=10, window=100, group=self.group, reset_time=expected_reset_time, remaining=0, concurrent_limit=settings.SENTRY_CONCURRENT_RATE_LIMIT_DEFAULT, concurrent_requests=None, ) for i in range(10): return_val = above_rate_limit_check( "bar", RateLimit(limit=120, window=100, concurrent_limit=9), f"request_uid{i}", self.group, ) assert return_val == RateLimitMeta( rate_limit_type=RateLimitType.CONCURRENT, current=10, limit=120, window=100, group=self.group, reset_time=expected_reset_time, remaining=110, concurrent_limit=9, concurrent_requests=9, ) def test_concurrent(self) -> None: def do_request() -> RateLimitMeta: uid = uuid.uuid4().hex meta = above_rate_limit_check( "foo", RateLimit(limit=10, window=1, concurrent_limit=3), uid, self.group ) sleep(0.2) finish_request("foo", uid) return meta with ThreadPoolExecutor(max_workers=4) as executor: futures = [] for _ in range(4): futures.append(executor.submit(do_request)) results = [] for f in futures: results.append(f.result()) assert len([r for r in results if r.concurrent_remaining == 0]) == 2 def test_window_and_concurrent_limit(self) -> None: """Test that if there is a window limit and a concurrent limit, the FIXED_WINDOW limit takes precedence""" return_val = above_rate_limit_check( "xar", RateLimit(limit=0, window=100, concurrent_limit=0), "request_uid", self.group ) assert return_val.rate_limit_type == RateLimitType.FIXED_WINDOW assert return_val.concurrent_remaining is None
RatelimitMiddlewareTest
python
spack__spack
lib/spack/spack/test/util/path.py
{ "start": 4625, "end": 10090 }
class ____: @pytest.mark.parametrize("padded,fixed", zip(padded_lines, fixed_lines)) def test_padding_substitution(self, padded, fixed): """Ensure that all padded lines are unpadded correctly.""" assert fixed == sup.padding_filter(padded) def test_no_substitution(self): """Ensure that a line not containing one full path placeholder is not modified.""" partial = "--prefix=/Users/gamblin2/padding-log-test/opt/__spack_path_pla/darwin-bigsur-skylake/apple-clang-12.0.5/zlib-1.2.11-74mwnxgn6nujehpyyalhwizwojwn5zga'" # noqa: E501 assert sup.padding_filter(partial) == partial def test_short_substitution(self): """Ensure that a single placeholder path component is replaced""" short = "--prefix=/Users/gamblin2/padding-log-test/opt/__spack_path_placeholder__/darwin-bigsur-skylake/apple-clang-12.0.5/zlib-1.2.11-74mwnxgn6nujehpyyalhwizwojwn5zga'" # noqa: E501 short_subst = "--prefix=/Users/gamblin2/padding-log-test/opt/[padded-to-63-chars]/darwin-bigsur-skylake/apple-clang-12.0.5/zlib-1.2.11-74mwnxgn6nujehpyyalhwizwojwn5zga'" # noqa: E501 assert short_subst == sup.padding_filter(short) def test_partial_substitution(self): """Ensure that a single placeholder path component is replaced""" short = "--prefix=/Users/gamblin2/padding-log-test/opt/__spack_path_placeholder__/__spack_p/darwin-bigsur-skylake/apple-clang-12.0.5/zlib-1.2.11-74mwnxgn6nujehpyyalhwizwojwn5zga'" # noqa: E501 short_subst = "--prefix=/Users/gamblin2/padding-log-test/opt/[padded-to-73-chars]/darwin-bigsur-skylake/apple-clang-12.0.5/zlib-1.2.11-74mwnxgn6nujehpyyalhwizwojwn5zga'" # noqa: E501 assert short_subst == sup.padding_filter(short) def test_longest_prefix_re(self): """Test that longest_prefix_re generates correct regular expressions.""" assert "(s(?:t(?:r(?:i(?:ng?)?)?)?)?)" == sup.longest_prefix_re("string", capture=True) assert "(?:s(?:t(?:r(?:i(?:ng?)?)?)?)?)" == sup.longest_prefix_re("string", capture=False) def test_output_filtering(self, capfd, install_mockery, mutable_config): """Test filtering padding out of tty messages.""" long_path = "/" + "/".join([sup.SPACK_PATH_PADDING_CHARS] * 200) padding_string = "[padded-to-%d-chars]" % len(long_path) # test filtering when padding is enabled with spack.config.override("config:install_tree", {"padded_length": 256}): # tty.msg with filtering on the first argument with sup.filter_padding(): tty.msg("here is a long path: %s/with/a/suffix" % long_path) out, err = capfd.readouterr() assert padding_string in out # tty.msg with filtering on a laterargument with sup.filter_padding(): tty.msg("here is a long path:", "%s/with/a/suffix" % long_path) out, err = capfd.readouterr() assert padding_string in out # tty.error with filtering on the first argument with sup.filter_padding(): tty.error("here is a long path: %s/with/a/suffix" % long_path) out, err = capfd.readouterr() assert padding_string in err # tty.error with filtering on a later argument with sup.filter_padding(): tty.error("here is a long path:", "%s/with/a/suffix" % long_path) out, err = capfd.readouterr() assert padding_string in err # test no filtering tty.msg("here is a long path: %s/with/a/suffix" % long_path) out, err = capfd.readouterr() assert padding_string not in out def test_pad_on_path_sep_boundary(self): """Ensure that padded paths do not end with path separator.""" pad_length = len(sup.SPACK_PATH_PADDING_CHARS) padded_length = 128 remainder = padded_length % (pad_length + 1) path = "a" * (remainder - 1) result = sup.add_padding(path, padded_length) assert 128 == len(result) and not result.endswith(os.path.sep) @pytest.mark.parametrize("debug", [1, 2]) def test_path_debug_padded_filter(debug, monkeypatch): """Ensure padded filter works as expected with different debug levels.""" fmt = "{0}{1}{2}{1}{3}" prefix = "[+] {0}home{0}user{0}install".format(os.sep) suffix = "mypackage" string = fmt.format(prefix, os.sep, os.sep.join([sup.SPACK_PATH_PADDING_CHARS] * 2), suffix) expected = ( fmt.format(prefix, os.sep, "[padded-to-{0}-chars]".format(72), suffix) if debug <= 1 and sys.platform != "win32" else string ) monkeypatch.setattr(tty, "_debug", debug) with spack.config.override("config:install_tree", {"padded_length": 128}): assert expected == sup.debug_padded_filter(string) @pytest.mark.parametrize( "path,expected", [ ("/home/spack/path/to/file.txt", "/home/spack/path/to/file.txt"), ("file:///home/another/config.yaml", "/home/another/config.yaml"), ("path/to.txt", os.path.join(spack.paths.spack_root, "path", "to.txt")), (r"C:\Files (x86)\Windows\10", r"C:\Files (x86)\Windows\10"), (r"E:/spack stage", "E:\\spack stage"), ], ) def test_canonicalize_file(path, expected): """Confirm canonicalize path handles local files and file URLs.""" assert sup.canonicalize_path(path) == os.path.normpath(expected)
TestPathPadding
python
anthropics__anthropic-sdk-python
src/anthropic/types/beta/beta_raw_content_block_start_event.py
{ "start": 1866, "end": 2067 }
class ____(BaseModel): content_block: ContentBlock """Response model for a file uploaded to the container.""" index: int type: Literal["content_block_start"]
BetaRawContentBlockStartEvent
python
gevent__gevent
src/gevent/exceptions.py
{ "start": 1607, "end": 1811 }
class ____(AssertionError): """ Raised when a gevent synchronous function is called from a low-level event loop callback. This is usually a programming error. """
BlockingSwitchOutError
python
numpy__numpy
numpy/tests/test_warnings.py
{ "start": 485, "end": 2420 }
class ____(ast.NodeVisitor): def __init__(self, filename): super().__init__() self.__filename = filename def visit_Call(self, node): p = ParseCall() p.visit(node.func) ast.NodeVisitor.generic_visit(self, node) if p.ls[-1] == 'simplefilter' or p.ls[-1] == 'filterwarnings': if getattr(node.args[0], "value", None) == "ignore": if not self.__filename.name.startswith("test_"): raise AssertionError( "ignore filters should only be used in tests; " f"found in {self.__filename} on line {node.lineno}") if p.ls[-1] == 'warn' and ( len(p.ls) == 1 or p.ls[-2] == 'warnings'): if "testing/tests/test_warnings.py" == self.__filename: # This file return # See if stacklevel exists: if len(node.args) == 3: return args = {kw.arg for kw in node.keywords} if "stacklevel" in args: return raise AssertionError( "warnings should have an appropriate stacklevel; " f"found in {self.__filename} on line {node.lineno}") @pytest.mark.slow def test_warning_calls(): # combined "ignore" and stacklevel error base = Path(numpy.__file__).parent for path in base.rglob("*.py"): if base / "testing" in path.parents: continue if path == base / "__init__.py": continue if path == base / "random" / "__init__.py": continue if path == base / "conftest.py": continue # use tokenize to auto-detect encoding on systems where no # default encoding is defined (e.g. LANG='C') with tokenize.open(str(path)) as file: tree = ast.parse(file.read()) FindFuncs(path).visit(tree)
FindFuncs
python
python__mypy
mypy/stubgen.py
{ "start": 13781, "end": 14854 }
class ____(mypy.traverser.TraverserVisitor): """Find names of things defined at the top level of a module.""" def __init__(self) -> None: # Short names of things defined at the top level. self.names: set[str] = set() def visit_class_def(self, o: ClassDef) -> None: # Don't recurse into classes, as we only keep track of top-level definitions. self.names.add(o.name) def visit_func_def(self, o: FuncDef) -> None: # Don't recurse, as we only keep track of top-level definitions. self.names.add(o.name) def visit_assignment_stmt(self, o: AssignmentStmt) -> None: for name in get_assigned_names(o.lvalues): self.names.add(name) def visit_type_alias_stmt(self, o: TypeAliasStmt) -> None: self.names.add(o.name.name) def find_referenced_names(file: MypyFile) -> set[str]: finder = ReferenceFinder() file.accept(finder) return finder.refs def is_none_expr(expr: Expression) -> bool: return isinstance(expr, NameExpr) and expr.name == "None"
DefinitionFinder
python
ray-project__ray
python/ray/experimental/channel/communicator_handle.py
{ "start": 38, "end": 689 }
class ____: """ A lightweight communicator handle used by the driver to store handles to the actors in the communicator. """ def __init__( self, actor_handles: List["ray.actor.ActorHandle"], ): """ Initializes the CommunicatorHandle with the given actor handles. Args: actor_handles: A list of actor handles to be stored. """ self._actor_handles = actor_handles def get_actor_handles(self) -> List["ray.actor.ActorHandle"]: """ Retuan all actor handles in this communicator. """ return self._actor_handles
CommunicatorHandle
python
dask__dask
dask/dataframe/dask_expr/_reductions.py
{ "start": 11822, "end": 17645 }
class ____(Expr): """Perform reduction-like operation on dataframes This pattern is commonly used for reductions, groupby-aggregations, and more. It requires three methods to be implemented: - `chunk`: applied to each input partition - `combine`: applied to lists of intermediate partitions as they are combined in batches - `aggregate`: applied at the end to finalize the computation These methods should be easy to serialize, and can take in keyword arguments defined in `chunks/combine/aggregate_kwargs`. In many cases people don't define all three functions. In these cases combine takes from aggregate and aggregate takes from chunk. """ _parameters = ["frame"] chunk: Callable | None = None combine: Callable | None = None aggregate: Callable | None = None chunk_kwargs: dict = {} combine_kwargs: dict = {} aggregate_args: list = [] aggregate_kwargs: dict = {} _chunk_cls = Chunk @property def split_out(self): if "split_out" in self._parameters: split_out = self.operand("split_out") if isinstance(split_out, Callable): split_out = split_out(self.frame.npartitions) if split_out is None: raise ValueError("split_out can't be None") return split_out else: return 1 def _layer(self): # This is an abstract expression raise NotImplementedError() @functools.cached_property def _meta_chunk(self): meta = meta_nonempty(self.frame._meta) return self.chunk(meta, **self.chunk_kwargs) @functools.cached_property def _meta(self): meta = self._meta_chunk aggregate = self.aggregate or (lambda x: x) if self.combine: combine = self.combine combine_kwargs = self.combine_kwargs else: combine = aggregate combine_kwargs = self.aggregate_kwargs meta = combine([meta], **combine_kwargs) meta = aggregate([meta], **self.aggregate_kwargs) return make_meta(meta) def _divisions(self): if getattr(self, "sort", False): return (None, None) if self.split_out is True: return (None,) * (self.frame.npartitions + 1) return (None,) * (self.split_out + 1) @property def _chunk_cls_args(self): return [] @property def should_shuffle(self): sort = getattr(self, "sort", False) return not ( not isinstance(self.split_out, bool) and self.split_out == 1 or sort ) @functools.cached_property def need_to_shuffle(self): split_by = self.split_by or self.frame.columns if any( set(split_by) >= (set(cols) if isinstance(cols, tuple) else {cols}) for cols in self.frame.unique_partition_mapping_columns_from_shuffle ): return False return True @functools.cached_property def unique_partition_mapping_columns_from_shuffle(self): if self.should_shuffle and not self.need_to_shuffle: return self.frame.unique_partition_mapping_columns_from_shuffle elif self.should_shuffle: return ( {self.split_by} if not isinstance(self.split_by, list) else {tuple(self.split_by)} ) else: return set() def _lower(self): # Normalize functions in case not all are defined chunk = self.chunk chunk_kwargs = self.chunk_kwargs if self.aggregate: aggregate = self.aggregate aggregate_kwargs = self.aggregate_kwargs else: aggregate = chunk aggregate_kwargs = chunk_kwargs if self.combine: combine = self.combine combine_kwargs = self.combine_kwargs else: combine = aggregate combine_kwargs = aggregate_kwargs split_every = getattr(self, "split_every", None) chunked = self._chunk_cls( self.frame, type(self), chunk, chunk_kwargs, *self._chunk_cls_args ) if not self.should_shuffle: # Lower into TreeReduce(Chunk) return TreeReduce( chunked, type(self), self._meta, combine, aggregate, combine_kwargs, aggregate_kwargs, split_every=split_every, ) elif not self.need_to_shuffle: # Repartition and return result = Aggregate( chunked, type(self), aggregate, aggregate_kwargs, *self.aggregate_args, ) if self.split_out is not True and self.split_out < result.npartitions: from dask.dataframe.dask_expr import Repartition return Repartition(result, new_partitions=self.split_out) if self.ndim < result.ndim: result = result[result.columns[0]] return result # Lower into ShuffleReduce return ShuffleReduce( chunked, type(self), self._meta, combine, aggregate, combine_kwargs, self.aggregate_args, aggregate_kwargs, split_by=self.split_by, split_out=self.split_out, split_every=split_every, sort=getattr(self, "sort", False), shuffle_by_index=getattr(self, "shuffle_by_index", None), shuffle_method=getattr(self, "shuffle_method", None), ignore_index=getattr(self, "ignore_index", True), )
ApplyConcatApply
python
bokeh__bokeh
src/bokeh/document/events.py
{ "start": 25866, "end": 27702 }
class ____(DocumentPatchedEvent): ''' A concrete event representing a change to remove an existing Model from a Document's collection of "root" models. ''' kind = "RootRemoved" def __init__(self, document: Document, model: Model, setter: Setter | None = None, callback_invoker: Invoker | None = None) -> None: ''' Args: document (Document) : A Bokeh document that is to be updated. model (Model) : The Bokeh Model to remove as a Document root. setter (ClientSession or ServerSession or None, optional) : This is used to prevent "boomerang" updates to Bokeh apps. (default: None) See :class:`~bokeh.document.events.DocumentChangedEvent` for more details. callback_invoker (callable, optional) : A callable that will invoke any Model callbacks that should be executed in response to the change that triggered this event. (default: None) ''' super().__init__(document, setter, callback_invoker) self.model = model def to_serializable(self, serializer: Serializer) -> RootRemoved: ''' Create a JSON representation of this event suitable for sending to clients. .. code-block:: python { 'kind' : 'RootRemoved' 'title' : <reference to a Model> } Args: serializer (Serializer): ''' return RootRemoved( kind = self.kind, model = self.model.ref, ) @staticmethod def _handle_event(doc: Document, event: RootRemovedEvent) -> None: model = event.model doc.remove_root(model, event.setter)
RootRemovedEvent
python
walkccc__LeetCode
solutions/2892. Minimizing Array After Replacing Pairs With Their Product/2892.py
{ "start": 0, "end": 291 }
class ____: def minArrayLength(self, nums: list[int], k: int) -> int: count = 0 prod = -1 for num in nums: if num == 0: return 1 if prod != -1 and prod * num <= k: prod *= num else: prod = num count += 1 return count
Solution
python
run-llama__llama_index
llama-index-core/llama_index/core/instrumentation/events/chat_engine.py
{ "start": 334, "end": 591 }
class ____(BaseEvent): """ StreamChatEndEvent. Fired at the end of writing to the stream chat-engine queue. """ @classmethod def class_name(cls) -> str: """Class name.""" return "StreamChatEndEvent"
StreamChatEndEvent
python
getsentry__sentry
src/sentry/issues/ownership/grammar.py
{ "start": 2929, "end": 7560 }
class ____(namedtuple("Matcher", "type pattern")): """ A Matcher represents a type:pattern pairing for use in comparing with an Event. type is either `path`, `tags`, `url`, `module` or `codeowners` at this point. TODO(mattrobenolt): pattern needs to be parsed into a regex Examples: url:example.com path:src/* src/* """ def __str__(self) -> str: return f"{self.type}:{self.pattern}" def dump(self) -> dict[str, str]: return {"type": self.type, "pattern": self.pattern} @classmethod def load(cls, data: Mapping[str, str]) -> Matcher: return cls(data["type"], data["pattern"]) @staticmethod def munge_if_needed( data: Mapping[str, Any], ) -> tuple[Sequence[Mapping[str, Any]], Sequence[str]]: keys = ["filename", "abs_path"] platform = data.get("platform") sdk_name = get_sdk_name(data) frames = find_stack_frames(data) if platform: munged = munged_filename_and_frames(platform, frames, "munged_filename", sdk_name) if munged: keys.append(munged[0]) frames = munged[1] return frames, keys def test( self, data: Mapping[str, Any], munged_data: tuple[Sequence[Mapping[str, Any]], Sequence[str]], ) -> bool: if self.type == URL: return self.test_url(data) elif self.type == PATH: return self.test_frames(*munged_data) elif self.type == MODULE: return self.test_frames(find_stack_frames(data), ["module"]) elif self.type.startswith("tags."): return self.test_tag(data) elif self.type == CODEOWNERS: return self.test_frames( *munged_data, # Codeowners has a slightly different syntax compared to issue owners # As such we need to match it using gitignore logic. # See syntax documentation here: # https://docs.github.com/en/github/creating-cloning-and-archiving-repositories/creating-a-repository-on-github/about-code-owners match_frame_value_func=lambda val, pattern: bool(codeowners_match(val, pattern)), match_frame_func=lambda frame: frame.get("in_app") is not False, ) return False def test_url(self, data: Mapping[str, Any]) -> bool: url = get_path(data, "request", "url") return url and bool(glob_match(url, self.pattern, ignorecase=True)) def test_frames( self, frames: Sequence[Mapping[str, Any]], keys: Sequence[str], match_frame_value_func: Callable[[str | None, str], bool] = lambda val, pattern: bool( glob_match(val, pattern, ignorecase=True, path_normalize=True) ), match_frame_func: Callable[[Mapping[str, Any]], bool] = lambda _: True, ) -> bool: for frame in frames: if not match_frame_func(frame): continue for key in keys: value = frame.get(key) if not value: continue if match_frame_value_func(value, self.pattern): return True return False def test_tag(self, data: Mapping[str, Any]) -> bool: tag = self.type[5:] # inspect the event-payload User interface first before checking tags.user if tag and tag.startswith("user."): for k, v in (get_path(data, "user", filter=True) or {}).items(): if isinstance(v, str) and tag.endswith("." + k) and glob_match(v, self.pattern): return True # user interface supports different fields in the payload, any other fields present gets put into the # 'data' dict # we look one more level deep to see if the pattern matches elif k == "data": for data_k, data_v in (v or {}).items(): if ( isinstance(data_v, str) and tag.endswith("." + data_k) and glob_match(data_v, self.pattern) ): return True for k, v in get_path(data, "tags", filter=True) or (): if k == tag and glob_match(v, self.pattern): return True elif k == EventSubjectTemplateData.tag_aliases.get(tag, tag) and glob_match( v, self.pattern ): return True return False
Matcher
python
pytorch__pytorch
test/distributed/launcher/api_test.py
{ "start": 3031, "end": 3137 }
class ____(Exception): pass def short_hash(): return str(uuid.uuid4()).split("-")[0]
MockException
python
pandas-dev__pandas
pandas/tests/window/test_groupby.py
{ "start": 1159, "end": 36048 }
class ____: def test_groupby_unsupported_argument(self, roll_frame): msg = r"groupby\(\) got an unexpected keyword argument 'foo'" with pytest.raises(TypeError, match=msg): roll_frame.groupby("A", foo=1) def test_getitem(self, roll_frame): g = roll_frame.groupby("A") g_mutated = get_groupby(roll_frame, by="A") expected = g_mutated.B.apply(lambda x: x.rolling(2).mean()) result = g.rolling(2).mean().B tm.assert_series_equal(result, expected) result = g.rolling(2).B.mean() tm.assert_series_equal(result, expected) result = g.B.rolling(2).mean() tm.assert_series_equal(result, expected) result = roll_frame.B.groupby(roll_frame.A).rolling(2).mean() tm.assert_series_equal(result, expected) def test_getitem_multiple(self, roll_frame): # GH 13174 g = roll_frame.groupby("A") r = g.rolling(2, min_periods=0) g_mutated = get_groupby(roll_frame, by="A") expected = g_mutated.B.apply(lambda x: x.rolling(2, min_periods=0).count()) result = r.B.count() tm.assert_series_equal(result, expected) result = r.B.count() tm.assert_series_equal(result, expected) @pytest.mark.parametrize( "f", [ "sum", "mean", "min", "max", "first", "last", "count", "kurt", "skew", "nunique", ], ) def test_rolling(self, f, roll_frame): g = roll_frame.groupby("A", group_keys=False) r = g.rolling(window=4) result = getattr(r, f)() expected = g.apply(lambda x: getattr(x.rolling(4), f)()) # GH 39732 expected_index = MultiIndex.from_arrays([roll_frame["A"], range(40)]) expected.index = expected_index tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("f", ["std", "var"]) def test_rolling_ddof(self, f, roll_frame): g = roll_frame.groupby("A", group_keys=False) r = g.rolling(window=4) result = getattr(r, f)(ddof=1) expected = g.apply(lambda x: getattr(x.rolling(4), f)(ddof=1)) # GH 39732 expected_index = MultiIndex.from_arrays([roll_frame["A"], range(40)]) expected.index = expected_index tm.assert_frame_equal(result, expected) @pytest.mark.parametrize( "interpolation", ["linear", "lower", "higher", "midpoint", "nearest"] ) def test_rolling_quantile(self, interpolation, roll_frame): g = roll_frame.groupby("A", group_keys=False) r = g.rolling(window=4) result = r.quantile(0.4, interpolation=interpolation) expected = g.apply( lambda x: x.rolling(4).quantile(0.4, interpolation=interpolation) ) # GH 39732 expected_index = MultiIndex.from_arrays([roll_frame["A"], range(40)]) expected.index = expected_index tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("f, expected_val", [["corr", 1], ["cov", 0.5]]) def test_rolling_corr_cov_other_same_size_as_groups(self, f, expected_val): # GH 42915 df = DataFrame( {"value": range(10), "idx1": [1] * 5 + [2] * 5, "idx2": [1, 2, 3, 4, 5] * 2} ).set_index(["idx1", "idx2"]) other = DataFrame({"value": range(5), "idx2": [1, 2, 3, 4, 5]}).set_index( "idx2" ) result = getattr(df.groupby(level=0).rolling(2), f)(other) expected_data = ([np.nan] + [expected_val] * 4) * 2 expected = DataFrame( expected_data, columns=["value"], index=MultiIndex.from_arrays( [ [1] * 5 + [2] * 5, [1] * 5 + [2] * 5, list(range(1, 6)) * 2, ], names=["idx1", "idx1", "idx2"], ), ) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("f", ["corr", "cov"]) def test_rolling_corr_cov_other_diff_size_as_groups(self, f, roll_frame): g = roll_frame.groupby("A") r = g.rolling(window=4) result = getattr(r, f)(roll_frame) def func(x): return getattr(x.rolling(4), f)(roll_frame) expected = g.apply(func) # GH 39591: The grouped column should be all np.nan # (groupby.apply inserts 0s for cov) expected["A"] = np.nan tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("f", ["corr", "cov"]) def test_rolling_corr_cov_pairwise(self, f, roll_frame): g = roll_frame.groupby("A") r = g.rolling(window=4) result = getattr(r.B, f)(pairwise=True) def func(x): return getattr(x.B.rolling(4), f)(pairwise=True) expected = g.apply(func) tm.assert_series_equal(result, expected) @pytest.mark.parametrize( "func, expected_values", [("cov", [[1.0, 1.0], [1.0, 4.0]]), ("corr", [[1.0, 0.5], [0.5, 1.0]])], ) def test_rolling_corr_cov_unordered(self, func, expected_values): # GH 43386 df = DataFrame( { "a": ["g1", "g2", "g1", "g1"], "b": [0, 0, 1, 2], "c": [2, 0, 6, 4], } ) rol = df.groupby("a").rolling(3) result = getattr(rol, func)() expected = DataFrame( { "b": 4 * [np.nan] + expected_values[0] + 2 * [np.nan], "c": 4 * [np.nan] + expected_values[1] + 2 * [np.nan], }, index=MultiIndex.from_tuples( [ ("g1", 0, "b"), ("g1", 0, "c"), ("g1", 2, "b"), ("g1", 2, "c"), ("g1", 3, "b"), ("g1", 3, "c"), ("g2", 1, "b"), ("g2", 1, "c"), ], names=["a", None, None], ), ) tm.assert_frame_equal(result, expected) def test_rolling_apply(self, raw, roll_frame): g = roll_frame.groupby("A", group_keys=False) r = g.rolling(window=4) # reduction result = r.apply(lambda x: x.sum(), raw=raw) expected = g.apply(lambda x: x.rolling(4).apply(lambda y: y.sum(), raw=raw)) # GH 39732 expected_index = MultiIndex.from_arrays([roll_frame["A"], range(40)]) expected.index = expected_index tm.assert_frame_equal(result, expected) def test_rolling_apply_mutability(self): # GH 14013 df = DataFrame({"A": ["foo"] * 3 + ["bar"] * 3, "B": [1] * 6}) g = df.groupby("A") mi = MultiIndex.from_tuples( [("bar", 3), ("bar", 4), ("bar", 5), ("foo", 0), ("foo", 1), ("foo", 2)] ) mi.names = ["A", None] # Grouped column should not be a part of the output expected = DataFrame([np.nan, 2.0, 2.0] * 2, columns=["B"], index=mi) result = g.rolling(window=2).sum() tm.assert_frame_equal(result, expected) # Call an arbitrary function on the groupby g.sum() # Make sure nothing has been mutated result = g.rolling(window=2).sum() tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("expected_value,raw_value", [[1.0, True], [0.0, False]]) def test_groupby_rolling(self, expected_value, raw_value): # GH 31754 def isnumpyarray(x): return int(isinstance(x, np.ndarray)) df = DataFrame({"id": [1, 1, 1], "value": [1, 2, 3]}) result = df.groupby("id").value.rolling(1).apply(isnumpyarray, raw=raw_value) expected = Series( [expected_value] * 3, index=MultiIndex.from_tuples(((1, 0), (1, 1), (1, 2)), names=["id", None]), name="value", ) tm.assert_series_equal(result, expected) def test_groupby_rolling_center_center(self): # GH 35552 series = Series(range(1, 6)) result = series.groupby(series).rolling(center=True, window=3).mean() expected = Series( [np.nan] * 5, index=MultiIndex.from_tuples(((1, 0), (2, 1), (3, 2), (4, 3), (5, 4))), ) tm.assert_series_equal(result, expected) series = Series(range(1, 5)) result = series.groupby(series).rolling(center=True, window=3).mean() expected = Series( [np.nan] * 4, index=MultiIndex.from_tuples(((1, 0), (2, 1), (3, 2), (4, 3))), ) tm.assert_series_equal(result, expected) df = DataFrame({"a": ["a"] * 5 + ["b"] * 6, "b": range(11)}) result = df.groupby("a").rolling(center=True, window=3).mean() expected = DataFrame( [np.nan, 1, 2, 3, np.nan, np.nan, 6, 7, 8, 9, np.nan], index=MultiIndex.from_tuples( ( ("a", 0), ("a", 1), ("a", 2), ("a", 3), ("a", 4), ("b", 5), ("b", 6), ("b", 7), ("b", 8), ("b", 9), ("b", 10), ), names=["a", None], ), columns=["b"], ) tm.assert_frame_equal(result, expected) df = DataFrame({"a": ["a"] * 5 + ["b"] * 5, "b": range(10)}) result = df.groupby("a").rolling(center=True, window=3).mean() expected = DataFrame( [np.nan, 1, 2, 3, np.nan, np.nan, 6, 7, 8, np.nan], index=MultiIndex.from_tuples( ( ("a", 0), ("a", 1), ("a", 2), ("a", 3), ("a", 4), ("b", 5), ("b", 6), ("b", 7), ("b", 8), ("b", 9), ), names=["a", None], ), columns=["b"], ) tm.assert_frame_equal(result, expected) def test_groupby_rolling_center_on(self): # GH 37141 df = DataFrame( data={ "Date": date_range("2020-01-01", "2020-01-10"), "gb": ["group_1"] * 6 + ["group_2"] * 4, "value": range(10), } ) result = ( df.groupby("gb") .rolling(6, on="Date", center=True, min_periods=1) .value.mean() ) mi = MultiIndex.from_arrays([df["gb"], df["Date"]], names=["gb", "Date"]) expected = Series( [1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 7.0, 7.5, 7.5, 7.5], name="value", index=mi, ) tm.assert_series_equal(result, expected) @pytest.mark.parametrize("min_periods", [5, 4, 3]) def test_groupby_rolling_center_min_periods(self, min_periods): # GH 36040 df = DataFrame({"group": ["A"] * 10 + ["B"] * 10, "data": range(20)}) window_size = 5 result = ( df.groupby("group") .rolling(window_size, center=True, min_periods=min_periods) .mean() ) result = result.reset_index()[["group", "data"]] grp_A_mean = [1.0, 1.5, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 7.5, 8.0] grp_B_mean = [x + 10.0 for x in grp_A_mean] num_nans = max(0, min_periods - 3) # For window_size of 5 nans = [np.nan] * num_nans grp_A_expected = nans + grp_A_mean[num_nans : 10 - num_nans] + nans grp_B_expected = nans + grp_B_mean[num_nans : 10 - num_nans] + nans expected = DataFrame( {"group": ["A"] * 10 + ["B"] * 10, "data": grp_A_expected + grp_B_expected} ) tm.assert_frame_equal(result, expected) def test_groupby_subselect_rolling(self): # GH 35486 df = DataFrame( {"a": [1, 2, 3, 2], "b": [4.0, 2.0, 3.0, 1.0], "c": [10, 20, 30, 20]} ) result = df.groupby("a")[["b"]].rolling(2).max() expected = DataFrame( [np.nan, np.nan, 2.0, np.nan], columns=["b"], index=MultiIndex.from_tuples( ((1, 0), (2, 1), (2, 3), (3, 2)), names=["a", None] ), ) tm.assert_frame_equal(result, expected) result = df.groupby("a")["b"].rolling(2).max() expected = Series( [np.nan, np.nan, 2.0, np.nan], index=MultiIndex.from_tuples( ((1, 0), (2, 1), (2, 3), (3, 2)), names=["a", None] ), name="b", ) tm.assert_series_equal(result, expected) def test_groupby_rolling_custom_indexer(self): # GH 35557 class SimpleIndexer(BaseIndexer): def get_window_bounds( self, num_values=0, min_periods=None, center=None, closed=None, step=None, ): min_periods = self.window_size if min_periods is None else 0 end = np.arange(num_values, dtype=np.int64) + 1 start = end - self.window_size start[start < 0] = min_periods return start, end df = DataFrame( {"a": [1.0, 2.0, 3.0, 4.0, 5.0] * 3}, index=[0] * 5 + [1] * 5 + [2] * 5 ) result = ( df.groupby(df.index) .rolling(SimpleIndexer(window_size=3), min_periods=1) .sum() ) expected = df.groupby(df.index).rolling(window=3, min_periods=1).sum() tm.assert_frame_equal(result, expected) def test_groupby_rolling_subset_with_closed(self): # GH 35549 df = DataFrame( { "column1": range(8), "column2": range(8), "group": ["A"] * 4 + ["B"] * 4, "date": [ Timestamp(date) for date in ["2019-01-01", "2019-01-01", "2019-01-02", "2019-01-02"] ] * 2, } ) result = ( df.groupby("group").rolling("1D", on="date", closed="left")["column1"].sum() ) expected = Series( [np.nan, np.nan, 1.0, 1.0, np.nan, np.nan, 9.0, 9.0], index=MultiIndex.from_frame( df[["group", "date"]], names=["group", "date"], ), name="column1", ) tm.assert_series_equal(result, expected) def test_groupby_rolling_agg_namedagg(self): # GH#28333 df = DataFrame( { "kind": ["cat", "dog", "cat", "dog", "cat", "dog"], "height": [9.1, 6.0, 9.5, 34.0, 12.0, 8.0], "weight": [7.9, 7.5, 9.9, 198.0, 10.0, 42.0], } ) result = ( df.groupby("kind") .rolling(2) .agg( total_weight=NamedAgg(column="weight", aggfunc=sum), min_height=NamedAgg(column="height", aggfunc=min), ) ) expected = DataFrame( { "total_weight": [np.nan, 17.8, 19.9, np.nan, 205.5, 240.0], "min_height": [np.nan, 9.1, 9.5, np.nan, 6.0, 8.0], }, index=MultiIndex( [["cat", "dog"], [0, 1, 2, 3, 4, 5]], [[0, 0, 0, 1, 1, 1], [0, 2, 4, 1, 3, 5]], names=["kind", None], ), ) tm.assert_frame_equal(result, expected) def test_groupby_subset_rolling_subset_with_closed(self): # GH 35549 df = DataFrame( { "column1": range(8), "column2": range(8), "group": ["A"] * 4 + ["B"] * 4, "date": [ Timestamp(date) for date in ["2019-01-01", "2019-01-01", "2019-01-02", "2019-01-02"] ] * 2, } ) result = ( df.groupby("group")[["column1", "date"]] .rolling("1D", on="date", closed="left")["column1"] .sum() ) expected = Series( [np.nan, np.nan, 1.0, 1.0, np.nan, np.nan, 9.0, 9.0], index=MultiIndex.from_frame( df[["group", "date"]], names=["group", "date"], ), name="column1", ) tm.assert_series_equal(result, expected) @pytest.mark.parametrize("func", ["max", "min"]) def test_groupby_rolling_index_changed(self, func): # GH: #36018 nlevels of MultiIndex changed ds = Series( [1, 2, 2], index=MultiIndex.from_tuples( [("a", "x"), ("a", "y"), ("c", "z")], names=["1", "2"] ), name="a", ) result = getattr(ds.groupby(ds).rolling(2), func)() expected = Series( [np.nan, np.nan, 2.0], index=MultiIndex.from_tuples( [(1, "a", "x"), (2, "a", "y"), (2, "c", "z")], names=["a", "1", "2"] ), name="a", ) tm.assert_series_equal(result, expected) def test_groupby_rolling_empty_frame(self): # GH 36197 expected = DataFrame({"s1": []}) result = expected.groupby("s1").rolling(window=1).sum() # GH 32262 expected = expected.drop(columns="s1") # GH-38057 from_tuples gives empty object dtype, we now get float/int levels # expected.index = MultiIndex.from_tuples([], names=["s1", None]) expected.index = MultiIndex.from_product( [Index([], dtype="float64"), Index([], dtype="int64")], names=["s1", None] ) tm.assert_frame_equal(result, expected) expected = DataFrame({"s1": [], "s2": []}) result = expected.groupby(["s1", "s2"]).rolling(window=1).sum() # GH 32262 expected = expected.drop(columns=["s1", "s2"]) expected.index = MultiIndex.from_product( [ Index([], dtype="float64"), Index([], dtype="float64"), Index([], dtype="int64"), ], names=["s1", "s2", None], ) tm.assert_frame_equal(result, expected) def test_groupby_rolling_string_index(self): # GH: 36727 df = DataFrame( [ ["A", "group_1", Timestamp(2019, 1, 1, 9)], ["B", "group_1", Timestamp(2019, 1, 2, 9)], ["Z", "group_2", Timestamp(2019, 1, 3, 9)], ["H", "group_1", Timestamp(2019, 1, 6, 9)], ["E", "group_2", Timestamp(2019, 1, 20, 9)], ], columns=["index", "group", "eventTime"], ).set_index("index") groups = df.groupby("group") df["count_to_date"] = groups.cumcount() rolling_groups = groups.rolling("10D", on="eventTime") result = rolling_groups.apply(lambda df: df.shape[0]) expected = DataFrame( [ ["A", "group_1", Timestamp(2019, 1, 1, 9), 1.0], ["B", "group_1", Timestamp(2019, 1, 2, 9), 2.0], ["H", "group_1", Timestamp(2019, 1, 6, 9), 3.0], ["Z", "group_2", Timestamp(2019, 1, 3, 9), 1.0], ["E", "group_2", Timestamp(2019, 1, 20, 9), 1.0], ], columns=["index", "group", "eventTime", "count_to_date"], ).set_index(["group", "index"]) tm.assert_frame_equal(result, expected) def test_groupby_rolling_no_sort(self): # GH 36889 result = ( DataFrame({"foo": [2, 1], "bar": [2, 1]}) .groupby("foo", sort=False) .rolling(1) .min() ) expected = DataFrame( np.array([[2.0, 2.0], [1.0, 1.0]]), columns=["foo", "bar"], index=MultiIndex.from_tuples([(2, 0), (1, 1)], names=["foo", None]), ) # GH 32262 expected = expected.drop(columns="foo") tm.assert_frame_equal(result, expected) def test_groupby_rolling_count_closed_on(self, unit): # GH 35869 df = DataFrame( { "column1": range(6), "column2": range(6), "group": 3 * ["A", "B"], "date": date_range(end="20190101", periods=6, unit=unit), } ) msg = "'d' is deprecated and will be removed in a future version." with tm.assert_produces_warning(Pandas4Warning, match=msg): result = ( df.groupby("group") .rolling("3d", on="date", closed="left")["column1"] .count() ) dti = DatetimeIndex( [ "2018-12-27", "2018-12-29", "2018-12-31", "2018-12-28", "2018-12-30", "2019-01-01", ], dtype=f"M8[{unit}]", ) mi = MultiIndex.from_arrays( [ ["A", "A", "A", "B", "B", "B"], dti, ], names=["group", "date"], ) expected = Series( [np.nan, 1.0, 1.0, np.nan, 1.0, 1.0], name="column1", index=mi, ) tm.assert_series_equal(result, expected) @pytest.mark.parametrize( ("func", "kwargs", "expected_values"), [ ( "rolling", {"window": 2, "min_periods": 1}, [np.nan, 0.5, np.nan, 0.5, 0.5], ), ("expanding", {}, [np.nan, 0.5, np.nan, 0.5, (1 / 3) ** 0.5]), ], ) def test_groupby_rolling_sem(self, func, kwargs, expected_values): # GH: 26476 df = DataFrame( [["a", 1], ["a", 2], ["b", 1], ["b", 2], ["b", 3]], columns=["a", "b"] ) result = getattr(df.groupby("a"), func)(**kwargs).sem() expected = DataFrame( {"a": [np.nan] * 5, "b": expected_values}, index=MultiIndex.from_tuples( [("a", 0), ("a", 1), ("b", 2), ("b", 3), ("b", 4)], names=["a", None] ), ) # GH 32262 expected = expected.drop(columns="a") tm.assert_frame_equal(result, expected) @pytest.mark.parametrize( ("rollings", "key"), [({"on": "a"}, "a"), ({"on": None}, "index")] ) def test_groupby_rolling_nans_in_index(self, rollings, key): # GH: 34617 df = DataFrame( { "a": to_datetime(["2020-06-01 12:00", "2020-06-01 14:00", np.nan]), "b": [1, 2, 3], "c": [1, 1, 1], } ) if key == "index": df = df.set_index("a") with pytest.raises(ValueError, match=f"{key} values must not have NaT"): df.groupby("c").rolling("60min", **rollings) @pytest.mark.parametrize("group_keys", [True, False]) def test_groupby_rolling_group_keys(self, group_keys): # GH 37641 # GH 38523: GH 37641 actually was not a bug. # group_keys only applies to groupby.apply directly arrays = [["val1", "val1", "val2"], ["val1", "val1", "val2"]] index = MultiIndex.from_arrays(arrays, names=("idx1", "idx2")) s = Series([1, 2, 3], index=index) result = s.groupby(["idx1", "idx2"], group_keys=group_keys).rolling(1).mean() expected = Series( [1.0, 2.0, 3.0], index=MultiIndex.from_tuples( [ ("val1", "val1", "val1", "val1"), ("val1", "val1", "val1", "val1"), ("val2", "val2", "val2", "val2"), ], names=["idx1", "idx2", "idx1", "idx2"], ), ) tm.assert_series_equal(result, expected) def test_groupby_rolling_index_level_and_column_label(self): # The groupby keys should not appear as a resulting column arrays = [["val1", "val1", "val2"], ["val1", "val1", "val2"]] index = MultiIndex.from_arrays(arrays, names=("idx1", "idx2")) df = DataFrame({"A": [1, 1, 2], "B": range(3)}, index=index) result = df.groupby(["idx1", "A"]).rolling(1).mean() expected = DataFrame( {"B": [0.0, 1.0, 2.0]}, index=MultiIndex.from_tuples( [ ("val1", 1, "val1", "val1"), ("val1", 1, "val1", "val1"), ("val2", 2, "val2", "val2"), ], names=["idx1", "A", "idx1", "idx2"], ), ) tm.assert_frame_equal(result, expected) def test_groupby_rolling_resulting_multiindex(self): # a few different cases checking the created MultiIndex of the result # https://github.com/pandas-dev/pandas/pull/38057 # grouping by 1 columns -> 2-level MI as result df = DataFrame({"a": np.arange(8.0), "b": [1, 2] * 4}) result = df.groupby("b").rolling(3).mean() expected_index = MultiIndex.from_tuples( [(1, 0), (1, 2), (1, 4), (1, 6), (2, 1), (2, 3), (2, 5), (2, 7)], names=["b", None], ) tm.assert_index_equal(result.index, expected_index) def test_groupby_rolling_resulting_multiindex2(self): # grouping by 2 columns -> 3-level MI as result df = DataFrame({"a": np.arange(12.0), "b": [1, 2] * 6, "c": [1, 2, 3, 4] * 3}) result = df.groupby(["b", "c"]).rolling(2).sum() expected_index = MultiIndex.from_tuples( [ (1, 1, 0), (1, 1, 4), (1, 1, 8), (1, 3, 2), (1, 3, 6), (1, 3, 10), (2, 2, 1), (2, 2, 5), (2, 2, 9), (2, 4, 3), (2, 4, 7), (2, 4, 11), ], names=["b", "c", None], ) tm.assert_index_equal(result.index, expected_index) def test_groupby_rolling_resulting_multiindex3(self): # grouping with 1 level on dataframe with 2-level MI -> 3-level MI as result df = DataFrame({"a": np.arange(8.0), "b": [1, 2] * 4, "c": [1, 2, 3, 4] * 2}) df = df.set_index("c", append=True) result = df.groupby("b").rolling(3).mean() expected_index = MultiIndex.from_tuples( [ (1, 0, 1), (1, 2, 3), (1, 4, 1), (1, 6, 3), (2, 1, 2), (2, 3, 4), (2, 5, 2), (2, 7, 4), ], names=["b", None, "c"], ) tm.assert_index_equal(result.index, expected_index, exact="equiv") def test_groupby_rolling_object_doesnt_affect_groupby_apply(self, roll_frame): # GH 39732 g = roll_frame.groupby("A", group_keys=False) expected = g.apply(lambda x: x.rolling(4).sum()).index _ = g.rolling(window=4) result = g.apply(lambda x: x.rolling(4).sum()).index tm.assert_index_equal(result, expected) @pytest.mark.parametrize( ("window", "min_periods", "closed", "expected"), [ (2, 0, "left", [None, 0.0, 1.0, 1.0, None, 0.0, 1.0, 1.0]), (2, 2, "left", [None, None, 1.0, 1.0, None, None, 1.0, 1.0]), (4, 4, "left", [None, None, None, None, None, None, None, None]), (4, 4, "right", [None, None, None, 5.0, None, None, None, 5.0]), ], ) def test_groupby_rolling_var(self, window, min_periods, closed, expected): df = DataFrame([1, 2, 3, 4, 5, 6, 7, 8]) result = ( df.groupby([1, 2, 1, 2, 1, 2, 1, 2]) .rolling(window=window, min_periods=min_periods, closed=closed) .var(0) ) expected_result = DataFrame( np.array(expected, dtype="float64"), index=MultiIndex( levels=[np.array([1, 2]), [0, 1, 2, 3, 4, 5, 6, 7]], codes=[[0, 0, 0, 0, 1, 1, 1, 1], [0, 2, 4, 6, 1, 3, 5, 7]], ), ) tm.assert_frame_equal(result, expected_result) @pytest.mark.parametrize( "columns", [MultiIndex.from_tuples([("A", ""), ("B", "C")]), ["A", "B"]] ) def test_by_column_not_in_values(self, columns): # GH 32262 df = DataFrame([[1, 0]] * 20 + [[2, 0]] * 12 + [[3, 0]] * 8, columns=columns) g = df.groupby("A") original_obj = g.obj.copy(deep=True) r = g.rolling(4) result = r.sum() assert "A" not in result.columns tm.assert_frame_equal(g.obj, original_obj) def test_groupby_level(self): # GH 38523, 38787 arrays = [ ["Falcon", "Falcon", "Parrot", "Parrot"], ["Captive", "Wild", "Captive", "Wild"], ] index = MultiIndex.from_arrays(arrays, names=("Animal", "Type")) df = DataFrame({"Max Speed": [390.0, 350.0, 30.0, 20.0]}, index=index) result = df.groupby(level=0)["Max Speed"].rolling(2).sum() expected = Series( [np.nan, 740.0, np.nan, 50.0], index=MultiIndex.from_tuples( [ ("Falcon", "Falcon", "Captive"), ("Falcon", "Falcon", "Wild"), ("Parrot", "Parrot", "Captive"), ("Parrot", "Parrot", "Wild"), ], names=["Animal", "Animal", "Type"], ), name="Max Speed", ) tm.assert_series_equal(result, expected) @pytest.mark.parametrize( "by, expected_data", [ [["id"], {"num": [100.0, 150.0, 150.0, 200.0]}], [ ["id", "index"], { "date": [ Timestamp("2018-01-01"), Timestamp("2018-01-02"), Timestamp("2018-01-01"), Timestamp("2018-01-02"), ], "num": [100.0, 200.0, 150.0, 250.0], }, ], ], ) def test_as_index_false(self, by, expected_data, unit): # GH 39433 data = [ ["A", "2018-01-01", 100.0], ["A", "2018-01-02", 200.0], ["B", "2018-01-01", 150.0], ["B", "2018-01-02", 250.0], ] df = DataFrame(data, columns=["id", "date", "num"]) df["date"] = df["date"].astype(f"M8[{unit}]") df = df.set_index(["date"]) gp_by = [getattr(df, attr) for attr in by] result = ( df.groupby(gp_by, as_index=False).rolling(window=2, min_periods=1).mean() ) expected = {"id": ["A", "A", "B", "B"]} expected.update(expected_data) expected = DataFrame( expected, index=df.index, ) if "date" in expected_data: expected["date"] = expected["date"].astype(f"M8[{unit}]") tm.assert_frame_equal(result, expected) def test_nan_and_zero_endpoints(self, any_int_numpy_dtype): # https://github.com/twosigma/pandas/issues/53 typ = np.dtype(any_int_numpy_dtype).type size = 1000 idx = np.repeat(typ(0), size) idx[-1] = 1 val = 5e25 arr = np.repeat(val, size) arr[0] = np.nan arr[-1] = 0 df = DataFrame( { "index": idx, "adl2": arr, } ).set_index("index") result = df.groupby("index")["adl2"].rolling(window=10, min_periods=1).mean() expected = Series( arr, name="adl2", index=MultiIndex.from_arrays( [ Index([0] * 999 + [1], dtype=typ, name="index"), Index([0] * 999 + [1], dtype=typ, name="index"), ], ), ) tm.assert_series_equal(result, expected) def test_groupby_rolling_non_monotonic(self): # GH 43909 shuffled = [3, 0, 1, 2] sec = 1_000 df = DataFrame( [{"t": Timestamp(2 * x * sec), "x": x + 1, "c": 42} for x in shuffled] ) with pytest.raises(ValueError, match=r".* must be monotonic"): df.groupby("c").rolling(on="t", window="3s") def test_groupby_monotonic(self): # GH 15130 # we don't need to validate monotonicity when grouping # GH 43909 we should raise an error here to match # behaviour of non-groupby rolling. data = [ ["David", "1/1/2015", 100], ["David", "1/5/2015", 500], ["David", "5/30/2015", 50], ["David", "7/25/2015", 50], ["Ryan", "1/4/2014", 100], ["Ryan", "1/19/2015", 500], ["Ryan", "3/31/2016", 50], ["Joe", "7/1/2015", 100], ["Joe", "9/9/2015", 500], ["Joe", "10/15/2015", 50], ] df = DataFrame(data=data, columns=["name", "date", "amount"]) df["date"] = to_datetime(df["date"]) df = df.sort_values("date") expected = ( df.set_index("date") .groupby("name") .apply(lambda x: x.rolling("180D")["amount"].sum()) ) result = df.groupby("name").rolling("180D", on="date")["amount"].sum() tm.assert_series_equal(result, expected) def test_datelike_on_monotonic_within_each_group(self): # GH 13966 (similar to #15130, closed by #15175) # superseded by 43909 # GH 46061: OK if the on is monotonic relative to each each group dates = date_range(start="2016-01-01 09:30:00", periods=20, freq="s") df = DataFrame( { "A": [1] * 20 + [2] * 12 + [3] * 8, "B": np.concatenate((dates, dates)), "C": np.arange(40), } ) expected = ( df.set_index("B").groupby("A").apply(lambda x: x.rolling("4s")["C"].mean()) ) result = df.groupby("A").rolling("4s", on="B").C.mean() tm.assert_series_equal(result, expected) def test_datelike_on_not_monotonic_within_each_group(self): # GH 46061 df = DataFrame( { "A": [1] * 3 + [2] * 3, "B": [Timestamp(year, 1, 1) for year in [2020, 2021, 2019]] * 2, "C": range(6), } ) with pytest.raises(ValueError, match="Each group within B must be monotonic."): df.groupby("A").rolling("365D", on="B")
TestRolling
python
great-expectations__great_expectations
great_expectations/expectations/metrics/table_metrics/table_head.py
{ "start": 878, "end": 4641 }
class ____(TableMetricProvider): metric_name = "table.head" value_keys = ("n_rows", "fetch_all") default_kwarg_values = {"n_rows": 5, "fetch_all": False} @metric_value(engine=PandasExecutionEngine) def _pandas( cls, execution_engine: PandasExecutionEngine, metric_domain_kwargs: dict, metric_value_kwargs: dict, metrics: dict[str, Any], runtime_configuration: dict, ) -> pd.DataFrame: df, _, _ = execution_engine.get_compute_domain( metric_domain_kwargs, domain_type=MetricDomainTypes.TABLE ) if metric_value_kwargs.get("fetch_all", cls.default_kwarg_values["fetch_all"]): return df n_rows: int = ( metric_value_kwargs.get("n_rows") # type: ignore[assignment] # FIXME expected 'int', got 'Any | None' if metric_value_kwargs.get("n_rows") is not None else cls.default_kwarg_values["n_rows"] ) return df.head(n=n_rows) @metric_value(engine=SqlAlchemyExecutionEngine) def _sqlalchemy( cls, execution_engine: SqlAlchemyExecutionEngine, metric_domain_kwargs: dict, metric_value_kwargs: dict, metrics: dict[str, Any], runtime_configuration: dict, ) -> pd.DataFrame: selectable, _, _ = execution_engine.get_compute_domain( metric_domain_kwargs, domain_type=MetricDomainTypes.TABLE ) n_rows: int = ( metric_value_kwargs.get("n_rows") # type: ignore[assignment] # FIXME expected 'int', got 'Any | None' if metric_value_kwargs.get("n_rows") is not None else cls.default_kwarg_values["n_rows"] ) # None means no limit limit: int | None = n_rows if metric_value_kwargs["fetch_all"]: limit = None selectable = sa.select("*").select_from(selectable).limit(limit).selectable # type: ignore[assignment,arg-type] # FIXME CoP try: with execution_engine.get_connection() as con: df = pandas_read_sql( sql=selectable, con=con, ) except StopIteration: # empty table. At least try to get the column names validator = Validator(execution_engine=execution_engine) columns = validator.get_metric( MetricConfiguration("table.columns", metric_domain_kwargs) ) df = pd.DataFrame(columns=columns) return df # type: ignore[return-value] # FIXME CoP @metric_value(engine=SparkDFExecutionEngine) def _spark( cls, execution_engine: SparkDFExecutionEngine, metric_domain_kwargs: dict, metric_value_kwargs: dict, metrics: dict[str, Any], runtime_configuration: dict, ) -> pd.DataFrame: df, _, _ = execution_engine.get_compute_domain( metric_domain_kwargs, domain_type=MetricDomainTypes.TABLE ) rows: list[pyspark.Row] | list[dict] if metric_value_kwargs["fetch_all"]: rows = df.collect() else: n_rows: int = ( metric_value_kwargs.get("n_rows") # type: ignore[assignment] # FIXME expected 'int', got 'Any | None' if metric_value_kwargs.get("n_rows") is not None else cls.default_kwarg_values["n_rows"] ) if n_rows >= 0: rows = df.head(n=n_rows) else: rows = df.head(n=df.count() + n_rows) rows = [element.asDict() for element in rows] df = pd.DataFrame(data=rows) # type: ignore[assignment] # FIXME CoP return df # type: ignore[return-value] # FIXME CoP
TableHead
python
langchain-ai__langchain
libs/langchain_v1/langchain/agents/structured_output.py
{ "start": 3262, "end": 5691 }
class ____(Generic[SchemaT]): """Describes a structured output schema.""" schema: type[SchemaT] """The schema for the response, can be a Pydantic model, `dataclass`, `TypedDict`, or JSON schema dict.""" name: str """Name of the schema, used for tool calling. If not provided, the name will be the model name or `"response_format"` if it's a JSON schema. """ description: str """Custom description of the schema. If not provided, provided will use the model's docstring. """ schema_kind: SchemaKind """The kind of schema.""" json_schema: dict[str, Any] """JSON schema associated with the schema.""" strict: bool = False """Whether to enforce strict validation of the schema.""" def __init__( self, schema: type[SchemaT], *, name: str | None = None, description: str | None = None, strict: bool = False, ) -> None: """Initialize SchemaSpec with schema and optional parameters.""" self.schema = schema if name: self.name = name elif isinstance(schema, dict): self.name = str(schema.get("title", f"response_format_{str(uuid.uuid4())[:4]}")) else: self.name = str(getattr(schema, "__name__", f"response_format_{str(uuid.uuid4())[:4]}")) self.description = description or ( schema.get("description", "") if isinstance(schema, dict) else getattr(schema, "__doc__", None) or "" ) self.strict = strict if isinstance(schema, dict): self.schema_kind = "json_schema" self.json_schema = schema elif isinstance(schema, type) and issubclass(schema, BaseModel): self.schema_kind = "pydantic" self.json_schema = schema.model_json_schema() elif is_dataclass(schema): self.schema_kind = "dataclass" self.json_schema = TypeAdapter(schema).json_schema() elif is_typeddict(schema): self.schema_kind = "typeddict" self.json_schema = TypeAdapter(schema).json_schema() else: msg = ( f"Unsupported schema type: {type(schema)}. " f"Supported types: Pydantic models, dataclasses, TypedDicts, and JSON schema dicts." ) raise ValueError(msg) @dataclass(init=False)
_SchemaSpec
python
airbytehq__airbyte
airbyte-ci/connectors/pipelines/pipelines/airbyte_ci/connectors/test/steps/python_connectors.py
{ "start": 11077, "end": 14038 }
class ____(PytestStep): """A step to run the connector integration tests with Pytest.""" title = "Integration tests" test_directory_name = "integration_tests" bind_to_docker_host = True def get_test_steps(context: ConnectorTestContext) -> STEP_TREE: """ Get all the tests steps for a Python connector. """ return [ [StepToRun(id=CONNECTOR_TEST_STEP_ID.BUILD, step=BuildConnectorImages(context))], [ StepToRun( id=CONNECTOR_TEST_STEP_ID.UNIT, step=UnitTests(context, secrets=context.get_secrets_for_step_id(CONNECTOR_TEST_STEP_ID.UNIT)), args=lambda results: {"connector_under_test": results[CONNECTOR_TEST_STEP_ID.BUILD].output[LOCAL_BUILD_PLATFORM]}, depends_on=[CONNECTOR_TEST_STEP_ID.BUILD], ) ], [ StepToRun( id=CONNECTOR_TEST_STEP_ID.INTEGRATION, step=IntegrationTests(context, secrets=context.get_secrets_for_step_id(CONNECTOR_TEST_STEP_ID.INTEGRATION)), args=lambda results: {"connector_under_test": results[CONNECTOR_TEST_STEP_ID.BUILD].output[LOCAL_BUILD_PLATFORM]}, depends_on=[CONNECTOR_TEST_STEP_ID.BUILD], ), StepToRun( id=CONNECTOR_TEST_STEP_ID.PYTHON_CLI_VALIDATION, step=PyAirbyteValidation(context), args=lambda results: {"connector_under_test": results[CONNECTOR_TEST_STEP_ID.BUILD].output[LOCAL_BUILD_PLATFORM]}, depends_on=[CONNECTOR_TEST_STEP_ID.BUILD], ), StepToRun( id=CONNECTOR_TEST_STEP_ID.ACCEPTANCE, step=AcceptanceTests( context, concurrent_test_run=context.concurrent_cat, secrets=context.get_secrets_for_step_id(CONNECTOR_TEST_STEP_ID.ACCEPTANCE), ), args=lambda results: {"connector_under_test_container": results[CONNECTOR_TEST_STEP_ID.BUILD].output[LOCAL_BUILD_PLATFORM]}, depends_on=[CONNECTOR_TEST_STEP_ID.BUILD], ), StepToRun( id=CONNECTOR_TEST_STEP_ID.CONNECTOR_LIVE_TESTS, step=LiveTests(context), args=lambda results: {"connector_under_test_container": results[CONNECTOR_TEST_STEP_ID.BUILD].output[LOCAL_BUILD_PLATFORM]}, depends_on=[CONNECTOR_TEST_STEP_ID.BUILD], ), ], [ StepToRun( id=CONNECTOR_TEST_STEP_ID.INCREMENTAL_ACCEPTANCE, step=IncrementalAcceptanceTests(context, secrets=context.get_secrets_for_step_id(CONNECTOR_TEST_STEP_ID.ACCEPTANCE)), args=lambda results: {"current_acceptance_tests_result": results[CONNECTOR_TEST_STEP_ID.ACCEPTANCE]}, depends_on=[CONNECTOR_TEST_STEP_ID.ACCEPTANCE], ) ], ]
IntegrationTests
python
walkccc__LeetCode
solutions/3176. Find the Maximum Length of a Good Subsequence I/3176.py
{ "start": 0, "end": 727 }
class ____: def maximumLength(self, nums: list[int], k: int) -> int: # dp[count][num] := the maximum length of a good subsequence with at most # `count` indices where seq[i] != seq[i + 1] and it ends in `num`. dp = [collections.Counter() for _ in range(k + 1)] # maxLen[count] := the maximum length of a good subsequence with `count` # indices where seq[i] != seq[i + 1] maxLen = [0] * (k + 1) for num in nums: for count in range(k, -1, -1): # Append `num` to the subsequence. dp[count][num] += 1 if count > 0: dp[count][num] = max(dp[count][num], maxLen[count - 1] + 1) maxLen[count] = max(maxLen[count], dp[count][num]) return maxLen[k]
Solution
python
kamyu104__LeetCode-Solutions
Python/closest-subsequence-sum.py
{ "start": 61, "end": 1455 }
class ____(object): def minAbsDifference(self, nums, goal): """ :type nums: List[int] :type goal: int :rtype: int """ mx, mn = sum(x for x in nums if x > 0), sum(x for x in nums if x < 0) if goal > mx: return goal-mx if goal < mn: return mn-goal result = abs(goal) sums1 = set([0]) for i in xrange(len(nums)//2): for x in list(sums1): if x+nums[i] in sums1: continue sums1.add(x+nums[i]) result = min(result, abs(goal-x-nums[i])) # case of right half part is 0 sorted_sums1 = sorted(sums1) # Time: O((n/2) * 2^(n/2)) = O(n * 2^(n/2)), Space: O(2^(n/2)) sums2 = set([0]) for i in xrange(len(nums)//2, len(nums)): for x in list(sums2): if x+nums[i] in sums2: continue sums2.add(x+nums[i]) ni = bisect.bisect_left(sorted_sums1, goal-x-nums[i]) # Time: O(2^(n/2)) * O(n/2) if ni < len(sorted_sums1): result = min(result, abs(goal-x-nums[i]-sorted_sums1[ni])) if ni > 0: result = min(result, abs(goal-x-nums[i]-sorted_sums1[ni-1])) if result == 0: return result return result
Solution
python
gevent__gevent
src/greentest/3.11/signalinterproctester.py
{ "start": 164, "end": 3151 }
class ____(unittest.TestCase): def setUp(self): self.got_signals = {'SIGHUP': 0, 'SIGUSR1': 0, 'SIGALRM': 0} def sighup_handler(self, signum, frame): self.got_signals['SIGHUP'] += 1 def sigusr1_handler(self, signum, frame): self.got_signals['SIGUSR1'] += 1 raise SIGUSR1Exception def wait_signal(self, child, signame): if child is not None: # This wait should be interrupted by exc_class # (if set) child.wait() timeout = support.SHORT_TIMEOUT deadline = time.monotonic() + timeout while time.monotonic() < deadline: if self.got_signals[signame]: return signal.pause() self.fail('signal %s not received after %s seconds' % (signame, timeout)) def subprocess_send_signal(self, pid, signame): code = 'import os, signal; os.kill(%s, signal.%s)' % (pid, signame) args = [sys.executable, '-I', '-c', code] return subprocess.Popen(args) def test_interprocess_signal(self): # Install handlers. This function runs in a sub-process, so we # don't worry about re-setting the default handlers. signal.signal(signal.SIGHUP, self.sighup_handler) signal.signal(signal.SIGUSR1, self.sigusr1_handler) signal.signal(signal.SIGUSR2, signal.SIG_IGN) signal.signal(signal.SIGALRM, signal.default_int_handler) # Let the sub-processes know who to send signals to. pid = str(os.getpid()) with self.subprocess_send_signal(pid, "SIGHUP") as child: self.wait_signal(child, 'SIGHUP') self.assertEqual(self.got_signals, {'SIGHUP': 1, 'SIGUSR1': 0, 'SIGALRM': 0}) # gh-110033: Make sure that the subprocess.Popen is deleted before # the next test which raises an exception. Otherwise, the exception # may be raised when Popen.__del__() is executed and so be logged # as "Exception ignored in: <function Popen.__del__ at ...>". child = None gc.collect() with self.assertRaises(SIGUSR1Exception): with self.subprocess_send_signal(pid, "SIGUSR1") as child: self.wait_signal(child, 'SIGUSR1') self.assertEqual(self.got_signals, {'SIGHUP': 1, 'SIGUSR1': 1, 'SIGALRM': 0}) with self.subprocess_send_signal(pid, "SIGUSR2") as child: # Nothing should happen: SIGUSR2 is ignored child.wait() try: with self.assertRaises(KeyboardInterrupt): signal.alarm(1) self.wait_signal(None, 'SIGALRM') self.assertEqual(self.got_signals, {'SIGHUP': 1, 'SIGUSR1': 1, 'SIGALRM': 0}) finally: signal.alarm(0) if __name__ == "__main__": unittest.main()
InterProcessSignalTests
python
walkccc__LeetCode
solutions/472. Concatenated Words/472.py
{ "start": 0, "end": 445 }
class ____: def findAllConcatenatedWordsInADict(self, words: list[str]) -> list[str]: wordSet = set(words) @functools.lru_cache(None) def isConcat(word: str) -> bool: for i in range(1, len(word)): prefix = word[:i] suffix = word[i:] if prefix in wordSet and (suffix in wordSet or isConcat(suffix)): return True return False return [word for word in words if isConcat(word)]
Solution
python
PrefectHQ__prefect
src/prefect/server/database/orm_models.py
{ "start": 45131, "end": 45782 }
class ____(Base): __table_args__: Any = ( sa.Index( "uq_composite_trigger_child_firing__a_id__pt_id__ct__id", "automation_id", "parent_trigger_id", "child_trigger_id", unique=True, ), ) automation_id: Mapped[uuid.UUID] = mapped_column( sa.ForeignKey("automation.id", ondelete="CASCADE") ) parent_trigger_id: Mapped[uuid.UUID] child_trigger_id: Mapped[uuid.UUID] child_firing_id: Mapped[uuid.UUID] child_fired_at: Mapped[Optional[DateTime]] child_firing: Mapped[Firing] = mapped_column(Pydantic(Firing))
CompositeTriggerChildFiring
python
spack__spack
lib/spack/spack/fetch_strategy.py
{ "start": 66450, "end": 66930 }
class ____(spack.error.FetchError): """Raised when a version can't be deduced from a set of arguments.""" def __init__(self, pkg=None, version=None, **args): msg = "Could not guess a fetch strategy" if pkg: msg += " for {pkg}".format(pkg=pkg) if version: msg += "@{version}".format(version=version) long_msg = "with arguments: {args}".format(args=args) super().__init__(msg, long_msg)
InvalidArgsError
python
numba__numba
numba/tests/test_typeinfer.py
{ "start": 28710, "end": 29052 }
class ____(FunctionPass): """Dummy pass to add "cr" to compiler state to avoid errors in TyperCompiler since it doesn't have lowering. """ _name = "dummy_cr" def __init__(self): FunctionPass.__init__(self) def run_pass(self, state): state.cr = 1 # arbitrary non-None value return True
DummyCR
python
fastapi__sqlmodel
docs_src/tutorial/one/tutorial008_py310.py
{ "start": 63, "end": 1503 }
class ____(SQLModel, table=True): id: int | None = Field(default=None, primary_key=True) name: str = Field(index=True) secret_name: str age: int | None = Field(default=None, index=True) sqlite_file_name = "database.db" sqlite_url = f"sqlite:///{sqlite_file_name}" engine = create_engine(sqlite_url, echo=True) def create_db_and_tables(): SQLModel.metadata.create_all(engine) def create_heroes(): hero_1 = Hero(name="Deadpond", secret_name="Dive Wilson") hero_2 = Hero(name="Spider-Boy", secret_name="Pedro Parqueador") hero_3 = Hero(name="Rusty-Man", secret_name="Tommy Sharp", age=48) hero_4 = Hero(name="Tarantula", secret_name="Natalia Roman-on", age=32) hero_5 = Hero(name="Black Lion", secret_name="Trevor Challa", age=35) hero_6 = Hero(name="Dr. Weird", secret_name="Steve Weird", age=36) hero_7 = Hero(name="Captain North America", secret_name="Esteban Rogelios", age=93) with Session(engine) as session: session.add(hero_1) session.add(hero_2) session.add(hero_3) session.add(hero_4) session.add(hero_5) session.add(hero_6) session.add(hero_7) session.commit() def select_heroes(): with Session(engine) as session: hero = session.get(Hero, 1) print("Hero:", hero) def main(): create_db_and_tables() create_heroes() select_heroes() if __name__ == "__main__": main()
Hero
python
PrefectHQ__prefect
src/prefect/context.py
{ "start": 16653, "end": 18002 }
class ____(RunContext): """ The context for a task run. Data in this context is only available from within a task run function. Attributes: task: The task instance associated with the task run task_run: The API metadata for this task run """ task: "Task[Any, Any]" task_run: TaskRun log_prints: bool = False parameters: dict[str, Any] # Result handling result_store: ResultStore persist_result: bool = Field(default_factory=get_default_persist_setting_for_tasks) __var__: ClassVar[ContextVar[Self]] = ContextVar("task_run") def serialize(self: Self, include_secrets: bool = True) -> dict[str, Any]: serialized = self.model_dump( include={ "task_run", "task", "parameters", "log_prints", "start_time", "input_keyset", "persist_result", }, exclude_unset=True, context={"include_secrets": include_secrets}, ) if self.result_store: serialized["result_store"] = self.result_store.model_dump( serialize_as_any=True, exclude_unset=True, context={"include_secrets": include_secrets}, ) return serialized
TaskRunContext
python
wandb__wandb
wandb/sdk/artifacts/_generated/artifact_used_by.py
{ "start": 254, "end": 336 }
class ____(GQLResult): artifact: Optional[ArtifactUsedByArtifact]
ArtifactUsedBy
python
django__django
django/db/models/functions/window.py
{ "start": 292, "end": 404 }
class ____(Func): function = "CUME_DIST" output_field = FloatField() window_compatible = True
CumeDist
python
sphinx-doc__sphinx
tests/roots/test-root/autodoc_target.py
{ "start": 1375, "end": 1468 }
class ____(Base): def inheritedmeth(self): # no docstring here pass
Derived
python
kamyu104__LeetCode-Solutions
Python/largest-palindrome-product.py
{ "start": 1003, "end": 1751 }
class ____(object): def largestPalindrome(self, n): """ :type n: int :rtype: int """ def divide_ceil(a, b): return (a+b-1)//b if n == 1: return 9 upper, lower = 10**n-1, 10**(n-1) for i in reversed(xrange(lower, upper**2//(10**n)+1)): candidate = int(str(i) + str(i)[::-1]) for y in reversed(xrange(divide_ceil(lower, 11)*11, upper+1, 11)): # y must be divisible by 11 because even-number-length palindrome meets modulo 11 digit check if candidate//y > upper: break if candidate%y == 0 and lower <= candidate//y: return candidate%1337 return -1
Solution2
python
sqlalchemy__sqlalchemy
test/orm/inheritance/test_relationship.py
{ "start": 62151, "end": 64263 }
class ____( fixtures.DeclarativeMappedTest, testing.AssertsCompiledSQL ): """test for #5107""" __dialect__ = "default" @classmethod def setup_classes(cls): Base = cls.DeclarativeBasic class X(Base): __tablename__ = "x" id = Column(Integer, primary_key=True) a_id = Column(Integer, ForeignKey("a.id")) a = relationship("A", back_populates="x") class A(Base): __tablename__ = "a" id = Column(Integer, primary_key=True) b = relationship("B", back_populates="a") kind = Column(String(30)) x = relationship("X", back_populates="a") __mapper_args__ = { "polymorphic_identity": "a", "polymorphic_on": kind, "with_polymorphic": "*", } class B(A): a_id = Column(Integer, ForeignKey("a.id")) a = relationship( "A", back_populates="b", uselist=False, remote_side=A.id ) __mapper_args__ = {"polymorphic_identity": "b"} def test_contains_eager_multi_alias(self): X, B, A = self.classes("X", "B", "A") s = fixture_session() a_b_alias = aliased(B, name="a_b") b_x_alias = aliased(X, name="b_x") q = ( s.query(A) .outerjoin(A.b.of_type(a_b_alias)) .outerjoin(a_b_alias.x.of_type(b_x_alias)) .options( contains_eager(A.b.of_type(a_b_alias)).contains_eager( a_b_alias.x.of_type(b_x_alias) ) ) ) self.assert_compile( q, "SELECT b_x.id AS b_x_id, b_x.a_id AS b_x_a_id, a_b.id AS a_b_id, " "a_b.kind AS a_b_kind, a_b.a_id AS a_b_a_id, a.id AS a_id_1, " "a.kind AS a_kind, a.a_id AS a_a_id FROM a " "LEFT OUTER JOIN a AS a_b ON a.id = a_b.a_id AND a_b.kind IN " "(__[POSTCOMPILE_kind_1]) LEFT OUTER JOIN x AS b_x " "ON a_b.id = b_x.a_id", )
ContainsEagerMultipleOfType
python
keon__algorithms
algorithms/tree/trie/add_and_search.py
{ "start": 367, "end": 542 }
class ____(object): def __init__(self, letter, is_terminal=False): self.children = dict() self.letter = letter self.is_terminal = is_terminal
TrieNode
python
google__pytype
pytype/tools/xref/kythe.py
{ "start": 377, "end": 499 }
class ____: signature: str path: str language: str root: str corpus: str @dataclasses.dataclass(frozen=True)
VName
python
dagster-io__dagster
python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py
{ "start": 67091, "end": 67823 }
class ____(GeneratedAirbyteSource): @public def __init__(self, name: str, api_key: str, start_date: str): """Airbyte Source for Klaviyo. Documentation can be found at https://docs.airbyte.com/integrations/sources/klaviyo Args: name (str): The name of the destination. api_key (str): Klaviyo API Key. See our docs if you need help finding this key. start_date (str): UTC date and time in the format 2017-01-25T00:00:00Z. Any data before this date will not be replicated. """ self.api_key = check.str_param(api_key, "api_key") self.start_date = check.str_param(start_date, "start_date") super().__init__("Klaviyo", name)
KlaviyoSource
python
ijl__orjson
test/test_enum.py
{ "start": 337, "end": 378 }
class ____(enum.auto): A = "a"
AutoEnum
python
scipy__scipy
scipy/optimize/_shgo_lib/_vertex.py
{ "start": 1878, "end": 4530 }
class ____(VertexBase): """ Add homology properties of a scalar field f: R^n --> R associated with the geometry built from the VertexBase class """ def __init__(self, x, field=None, nn=None, index=None, field_args=(), g_cons=None, g_cons_args=()): """ Parameters ---------- x : tuple, vector of vertex coordinates field : callable, optional a scalar field f: R^n --> R associated with the geometry nn : list, optional list of nearest neighbours index : int, optional index of the vertex field_args : tuple, optional additional arguments to be passed to field g_cons : callable, optional constraints on the vertex g_cons_args : tuple, optional additional arguments to be passed to g_cons """ super().__init__(x, nn=nn, index=index) # Note Vertex is only initiated once for all x so only # evaluated once # self.feasible = None # self.f is externally defined by the cache to allow parallel # processing # None type that will break arithmetic operations unless defined # self.f = None self.check_min = True self.check_max = True def connect(self, v): """Connects self to another vertex object v. Parameters ---------- v : VertexBase or VertexScalarField object """ if v is not self and v not in self.nn: self.nn.add(v) v.nn.add(self) # Flags for checking homology properties: self.check_min = True self.check_max = True v.check_min = True v.check_max = True def disconnect(self, v): if v in self.nn: self.nn.remove(v) v.nn.remove(self) # Flags for checking homology properties: self.check_min = True self.check_max = True v.check_min = True v.check_max = True def minimiser(self): """Check whether this vertex is strictly less than all its neighbours""" if self.check_min: self._min = all(self.f < v.f for v in self.nn) self.check_min = False return self._min def maximiser(self): """ Check whether this vertex is strictly greater than all its neighbours. """ if self.check_max: self._max = all(self.f > v.f for v in self.nn) self.check_max = False return self._max
VertexScalarField
python
networkx__networkx
networkx/algorithms/tests/test_node_classification.py
{ "start": 2570, "end": 4663 }
class ____: def test_path_graph(self): G = nx.path_graph(4) label_name = "label" G.nodes[0][label_name] = "A" G.nodes[3][label_name] = "B" predicted = node_classification.local_and_global_consistency( G, label_name=label_name ) assert predicted[0] == "A" assert predicted[1] == "A" assert predicted[2] == "B" assert predicted[3] == "B" def test_no_labels(self): with pytest.raises(nx.NetworkXError): G = nx.path_graph(4) node_classification.local_and_global_consistency(G) def test_no_nodes(self): with pytest.raises(nx.NetworkXError): G = nx.Graph() node_classification.local_and_global_consistency(G) def test_no_edges(self): with pytest.raises(nx.NetworkXError): G = nx.Graph() G.add_node(1) G.add_node(2) node_classification.local_and_global_consistency(G) def test_digraph(self): with pytest.raises(nx.NetworkXNotImplemented): G = nx.DiGraph() G.add_edge(0, 1) G.add_edge(1, 2) G.add_edge(2, 3) label_name = "label" G.nodes[0][label_name] = "A" G.nodes[3][label_name] = "B" node_classification.harmonic_function(G) def test_one_labeled_node(self): G = nx.path_graph(4) label_name = "label" G.nodes[0][label_name] = "A" predicted = node_classification.local_and_global_consistency( G, label_name=label_name ) assert predicted[0] == "A" assert predicted[1] == "A" assert predicted[2] == "A" assert predicted[3] == "A" def test_nodes_all_labeled(self): G = nx.karate_club_graph() label_name = "club" predicted = node_classification.local_and_global_consistency( G, alpha=0, label_name=label_name ) for i in range(len(G)): assert predicted[i] == G.nodes[i][label_name]
TestLocalAndGlobalConsistency
python
kamyu104__LeetCode-Solutions
Python/find-the-encrypted-string.py
{ "start": 38, "end": 252 }
class ____(object): def getEncryptedString(self, s, k): """ :type s: str :type k: int :rtype: str """ return "".join(s[(i+k)%len(s)] for i in xrange(len(s)))
Solution
python
pytorch__pytorch
test/dynamo/test_streams.py
{ "start": 18245, "end": 22900 }
class ____(torch.nn.Module): def forward(self, tangents_1: "f32[2, 2]", tangents_2: "f32[2, 2]"): # Annotation: {'stream': 0} mul_2: "f32[2, 2]" = torch.ops.aten.mul.Tensor(tangents_2, 2) # add_2: "f32[2, 2]" = torch.ops.aten.add.Tensor(tangents_2, tangents_1); tangents_2 = None # Annotation: {'stream': 1} mul_3: "f32[2, 2]" = torch.ops.aten.mul.Tensor(tangents_1, 2); tangents_1 = None # No stacktrace found for following nodes record_event_default = torch.ops.streams.record_event.default(2, 1); record_event_default = None wait_event_default = torch.ops.streams.wait_event.default(2, 0); wait_event_default = None # Annotation: {'stream': 0} add_3: "f32[2, 2]" = torch.ops.aten.add.Tensor(mul_2, mul_3); mul_2 = mul_3 = None return (add_3, add_2) """, ) @requires_cuda def test_event_tracing(self): def fn(x) -> None: e = torch.Event() e.record() x.add_(1) return x inp = (torch.ones(2, 2, device="cuda"),) ( _, _, fw_graphs, _, ) = extract_graph(fn, *inp) self.assertExpectedInline( print_graph(fw_graphs[0]), """\ class <lambda>(torch.nn.Module): def forward(self, arg0_1: "f32[2, 2]"): # record_event = torch.ops.streams.record_event.default(0, 1); record_event = None # add: "f32[2, 2]" = torch.ops.aten.add.Tensor(arg0_1, 1) copy_: "f32[2, 2]" = torch.ops.aten.copy_.default(arg0_1, add); arg0_1 = add = None return (copy_,) """, ) @requires_cuda def test_run_opcheck_fork_join(self): from torch._dynamo.variables.streams import fork_stream, join_stream from torch.library import opcheck original_stream = torch.accelerator.current_stream() try: s0 = torch.Stream() s1 = torch.Stream() store_user_object_weakrefs(s0, s1) sample_inputs = [ (0, 1), (1, 0), ] for args in sample_inputs: opcheck(fork_stream, args) opcheck(join_stream, args) finally: torch.accelerator.set_stream(original_stream) reset_user_object_tracking() @requires_cuda def test_run_opcheck_wait_record(self): from torch._dynamo.variables.streams import record_event, wait_event from torch.library import opcheck original_stream = torch.accelerator.current_stream() try: s0 = torch.Stream() s1 = torch.Stream() e0 = torch.Event() e1 = torch.Event() store_user_object_weakrefs(s0, s1, e0, e1) sample_inputs = [ (2, 0), (3, 1), ] for args in sample_inputs: opcheck(wait_event, args) opcheck(record_event, args) finally: torch.accelerator.set_stream(original_stream) reset_user_object_tracking() @requires_cuda def test_run_opcheck_wait_record_stream(self): from torch._dynamo.variables.streams import wait_stream from torch.library import opcheck s0 = torch.Stream() s1 = torch.Stream() s2 = torch.Stream() store_user_object_weakrefs(s0, s1, s2) sample_inputs = [ (0, 1), (2, 0), ] for args in sample_inputs: opcheck(wait_stream, args) @requires_cuda def test_inductor_lowering(self): with patch("torch._inductor.config.implicit_fallbacks", False): @torch.compile() def fn(x): e = torch.Event() x += x + 1 e.record() return x inp = (torch.ones(2, 2, device="cuda"),) fn(*inp) def test_is_marked_side_effectful(self): self.assertIn( torch.ops.streams.fork.default, torch.fx.node._side_effectful_functions ) self.assertIn( torch.ops.streams.join.default, torch.fx.node._side_effectful_functions ) self.assertIn( torch.ops.streams.wait_event.default, torch.fx.node._side_effectful_functions, ) self.assertIn( torch.ops.streams.record_event.default, torch.fx.node._side_effectful_functions, ) if __name__ == "__main__": from torch._dynamo.test_case import run_tests run_tests()
GraphModule
python
numba__numba
numba/tests/test_listobject.py
{ "start": 14617, "end": 17699 }
class ____(MemoryLeakMixin, TestCase): """Test list setitem. """ def test_list_setitem_singleton(self): @njit def foo(n): l = listobject.new_list(int32) l.append(0) l[0] = n return l[0] for i in (0, 1, 2, 100): self.assertEqual(foo(i), i) def test_list_setitem_singleton_negative_index(self): @njit def foo(n): l = listobject.new_list(int32) l.append(0) l[0] = n return l[-1] for i in (0, 1, 2, 100): self.assertEqual(foo(i), i) def test_list_setitem_singleton_index_error(self): self.disable_leak_check() @njit def foo(i): l = listobject.new_list(int32) l.append(0) l[i] = 1 with self.assertRaises(IndexError): foo(1) with self.assertRaises(IndexError): foo(-2) def test_list_setitem_multiple(self): @njit def foo(i, n): l = listobject.new_list(int32) for j in range(10, 20): l.append(j) l[i] = n return l[i] for i,n in zip(range(0,10), range(20,30)): self.assertEqual(foo(i, n), n) def test_list_setitem_multiple_index_error(self): self.disable_leak_check() @njit def foo(i): l = listobject.new_list(int32) for j in range(10, 20): l.append(j) l[i] = 0 with self.assertRaises(IndexError): foo(10) with self.assertRaises(IndexError): foo(-11) def test_list_setitem_singleton_typing_error_on_index(self): self.disable_leak_check() @njit def foo(i): l = listobject.new_list(int32) l.append(0) # slice with a non-{integer,slice} l[i] = 1 for i in "xyz", 1.0, 1j: with self.assertRaises(TypingError) as raises: foo(i) self.assertIn( "list indices must be integers or slices", str(raises.exception), ) def test_list_setitem_singleton_typing_error_on_item(self): self.disable_leak_check() @njit def foo(): l = listobject.new_list(int32) l.append(0) # assign a non-iterable to a slice l[:] = 1 with self.assertRaises(TypingError) as raises: foo() self.assertIn( "can only assign an iterable when using a slice " "with assignment/setitem", str(raises.exception), ) def test_list_setitem_integer_types_as_index(self): @njit def foo(i): l = listobject.new_list(int32) l.append(0) l[i] = 1 return l[i] # try all signed integers and make sure they are cast for t in (types.signed_domain ): self.assertEqual(foo((t(0))), 1)
TestSetitem
python
django__django
django/contrib/postgres/fields/hstore.py
{ "start": 436, "end": 2529 }
class ____(CheckPostgresInstalledMixin, CheckFieldDefaultMixin, Field): empty_strings_allowed = False description = _("Map of strings to strings/nulls") default_error_messages = { "not_a_string": _("The value of “%(key)s” is not a string or null."), } _default_hint = ("dict", "{}") def db_type(self, connection): return "hstore" def get_transform(self, name): transform = super().get_transform(name) if transform: return transform return KeyTransformFactory(name) def validate(self, value, model_instance): super().validate(value, model_instance) for key, val in value.items(): if not isinstance(val, str) and val is not None: raise exceptions.ValidationError( self.error_messages["not_a_string"], code="not_a_string", params={"key": key}, ) def to_python(self, value): if isinstance(value, str): value = json.loads(value) return value def value_to_string(self, obj): return json.dumps(self.value_from_object(obj), ensure_ascii=False) def formfield(self, **kwargs): return super().formfield( **{ "form_class": forms.HStoreField, **kwargs, } ) def get_prep_value(self, value): value = super().get_prep_value(value) if isinstance(value, dict): prep_value = {} for key, val in value.items(): key = str(key) if val is not None: val = str(val) prep_value[key] = val value = prep_value if isinstance(value, list): value = [str(item) for item in value] return value HStoreField.register_lookup(lookups.DataContains) HStoreField.register_lookup(lookups.ContainedBy) HStoreField.register_lookup(lookups.HasKey) HStoreField.register_lookup(lookups.HasKeys) HStoreField.register_lookup(lookups.HasAnyKeys)
HStoreField
python
dagster-io__dagster
python_modules/dagster/dagster/components/component/component.py
{ "start": 2982, "end": 15387 }
class ____(ABC): """Abstract base class for creating Dagster components. Components are the primary building blocks for programmatically creating Dagster definitions. They enable building multiple interrelated definitions for specific use cases, provide schema-based configuration, and built-in scaffolding support to simplify component instantiation in projects. Components are automatically discovered by Dagster tooling and can be instantiated from YAML configuration files or Python code that conform to the declared schema. Key Capabilities: - **Definition Factory**: Creates Dagster assets, jobs, schedules, and other definitions - **Schema-Based Configuration**: Optional parameterization via YAML or Python objects - **Scaffolding Support**: Custom project structure generation via ``dg scaffold`` commands - **Tool Integration**: Automatic discovery by Dagster CLI and UI tools - **Testing Utilities**: Built-in methods for testing component behavior Implementing a component: - Every component must implement the ``build_defs()`` method, which serves as a factory for creating Dagster definitions. - Components can optionally inherit from ``Resolvable`` to add schema-based configuration capabilities, enabling parameterization through YAML files or structured Python objects. - Components can attach a custom scaffolder with the ``@scaffold_with`` decorator. Examples: Simple component with hardcoded definitions: .. code-block:: python import dagster as dg class SimpleDataComponent(dg.Component): \"\"\"Component that creates a toy, hardcoded data processing asset.\"\"\" def build_defs(self, context: dg.ComponentLoadContext) -> dg.Definitions: @dg.asset def raw_data(): return [1, 2, 3, 4, 5] @dg.asset def processed_data(raw_data): return [x * 2 for x in raw_data] return dg.Definitions(assets=[raw_data, processed_data]) Configurable component with schema: .. code-block:: python import dagster as dg from typing import List class DatabaseTableComponent(dg.Component, dg.Resolvable, dg.Model): \"\"\"Component for creating assets from database tables.\"\"\" table_name: str columns: List[str] database_url: str = "postgresql://localhost/mydb" def build_defs(self, context: dg.ComponentLoadContext) -> dg.Definitions: @dg.asset(key=f"{self.table_name}_data") def table_asset(): # Use self.table_name, self.columns, etc. return execute_query(f"SELECT {', '.join(self.columns)} FROM {self.table_name}") return dg.Definitions(assets=[table_asset]) Using the component in a YAML file (``defs.yaml``): .. code-block:: yaml type: my_project.components.DatabaseTableComponent attributes: table_name: "users" columns: ["id", "name", "email"] database_url: "postgresql://prod-db/analytics" Component Discovery: Components are automatically discovered by Dagster tooling when defined in modules specified in your project's ``pyproject.toml`` registry configuration: .. code-block:: toml [tool.dagster] module_name = "my_project" registry_modules = ["my_project.components"] This enables CLI commands like: .. code-block:: bash dg list components # List all available components in the Python environment dg scaffold defs MyComponent path/to/component # Generate component instance with scaffolding Schema and Configuration: To make a component configurable, inherit from both ``Component`` and ``Resolvable``, along with a model base class. Pydantic models and dataclasses are supported largely so that pre-existing code can be used as schema without having to modify it. We recommend using ``dg.Model`` for new components, which wraps Pydantic with Dagster defaults for better developer experience. - ``dg.Model``: Recommended for new components (wraps Pydantic with Dagster defaults) - ``pydantic.BaseModel``: Direct Pydantic usage - ``@dataclass``: Python dataclasses with validation Custom Scaffolding: Components can provide custom scaffolding behavior using the ``@scaffold_with`` decorator: .. code-block:: python import textwrap import dagster as dg from dagster.components import Scaffolder, ScaffoldRequest class DatabaseComponentScaffolder(Scaffolder): def scaffold(self, request: ScaffoldRequest) -> None: # Create component directory component_dir = request.target_path component_dir.mkdir(parents=True, exist_ok=True) # Generate defs.yaml with template defs_file = component_dir / "defs.yaml" defs_file.write_text( textwrap.dedent( f''' type: {request.type_name} attributes: table_name: "example_table" columns: ["id", "name"] database_url: "${{DATABASE_URL}}" '''.strip() ) ) # Generate SQL query template sql_file = component_dir / "query.sql" sql_file.write_text("SELECT * FROM example_table;") @dg.scaffold_with(DatabaseComponentScaffolder) class DatabaseTableComponent(dg.Component, dg.Resolvable, dg.Model): table_name: str columns: list[str] def build_defs(self, context: dg.ComponentLoadContext) -> dg.Definitions: # Component implementation pass See Also: * :py:class:`dagster.Definitions` The object returned by ``build_defs()`` * :py:class:`dagster.ComponentLoadContext` Context provided to ``build_defs()`` * :py:class:`dagster.components.resolved.base.Resolvable` Base for configurable components * :py:class:`dagster.Model` Recommended base class for component schemas * :py:func:`dagster.scaffold_with` Decorator for custom scaffolding """ @classmethod def get_decl_type(cls) -> type["ComponentDecl"]: from dagster.components.core.decl import YamlDecl return YamlDecl @classmethod def __dg_package_entry__(cls) -> None: ... @classmethod def get_schema(cls) -> Optional[type[BaseModel]]: return None @classmethod def get_spec(cls) -> ComponentTypeSpec: return ComponentTypeSpec() @classmethod def get_model_cls(cls) -> Optional[type[BaseModel]]: if issubclass(cls, Resolvable): return cls.model() # handle existing overrides for backwards compatibility cls_from_get_schema = cls.get_schema() if cls_from_get_schema: return cls_from_get_schema # explicitly mark that the component has no attributes return EmptyAttributesModel @classmethod def get_additional_scope(cls) -> Mapping[str, Any]: return get_context_free_static_template_vars(cls) @abstractmethod def build_defs(self, context: "ComponentLoadContext") -> Definitions: ... @classmethod def load(cls, attributes: Optional[BaseModel], context: "ComponentLoadContext") -> Self: if issubclass(cls, Resolvable): from dagster.components.resolved.scopes import DeprecatedScope, LoadContextScope # Wrap the context to expose it in templates template_ctx = LoadContextScope(context) context_with_injected_scope = context.with_rendering_scope( { # New namespaced access "context": template_ctx, # Backward compatibility - deprecated, will be removed in 1.13.0 "project_root": DeprecatedScope( "project_root", "context.project_root", template_ctx.project_root ), "load_component_at_path": DeprecatedScope( "load_component_at_path", "context.load_component", context.load_component_at_path, ), "build_defs_at_path": DeprecatedScope( "build_defs_at_path", "context.build_defs", context.build_defs_at_path, ), } ) return ( cls.resolve_from_model( context_with_injected_scope.resolution_context.at_path("attributes"), attributes, ) if attributes else cls() ) else: # If the Component does not implement anything from Resolved, try to instantiate it without # argument. return cls() @classmethod def get_code_references_for_yaml( cls, yaml_path: Path, source_position: SourcePosition, context: "ComponentLoadContext" ) -> Sequence[CodeReference]: """Returns a list of code references for a component which has been defined in a YAML file. Args: yaml_path (Path): The path to the YAML file where this component is defined. source_position (SourcePosition): The source position of the component in the YAML file. context (ComponentLoadContext): The context in which the component is being loaded. """ return [ LocalFileCodeReference(file_path=str(yaml_path), line_number=source_position.start.line) ] @classmethod def get_description(cls) -> Optional[str]: return cls.get_spec().description or inspect.getdoc(cls) @classmethod def from_attributes_dict( cls, *, attributes: dict, context: Optional["ComponentLoadContext"] = None ) -> Self: """Load a Component from a dictionary. The dictionary is what would exist in the component.yaml file under the "attributes" key. Examples: .. code-block:: python class ModelComponentWithDeclaration(Component, Model, Resolvable): value: str def build_defs(self, context: ComponentLoadContext) -> Definitions: ... assert ( component_defs( component=ModelComponentWithDeclaration.from_attributes_dict(attributes={"value": "foobar"}), ).get_assets_def("an_asset")() == "foobar" ) Args: attributes (dict): The attributes to load the Component from. context (Optional[ComponentLoadContext]): The context to load the Component from. Returns: A Component instance. """ from dagster.components.core.component_tree import ComponentTree model_cls = cls.get_model_cls() assert model_cls model = TypeAdapter(model_cls).validate_python(attributes) return cls.load(model, context if context else ComponentTree.for_test().load_context) @classmethod def from_yaml_path( cls, yaml_path: Path, context: Optional["ComponentLoadContext"] = None ) -> "Component": """Load a Component from a yaml file. Args: yaml_path (Path): The path to the yaml file. context (Optional[ComponentLoadContext]): The context to load the Component from. Defaults to a test context. Returns: A Component instance. """ from dagster.components.core.component_tree import ComponentTree from dagster.components.core.defs_module import load_yaml_component_from_path return load_yaml_component_from_path( context=context or ComponentTree.for_test().load_context, component_def_path=yaml_path, )
Component
python
apache__airflow
providers/teradata/src/airflow/providers/teradata/operators/bteq.py
{ "start": 1699, "end": 12656 }
class ____(BaseOperator): """ Teradata Operator to execute SQL Statements or BTEQ (Basic Teradata Query) scripts using Teradata BTEQ utility. This supports execution of BTEQ scripts either locally or remotely via SSH. The BTEQ scripts are used to interact with Teradata databases, allowing users to perform operations such as querying, data manipulation, and administrative tasks. Features: - Supports both local and remote execution of BTEQ scripts. - Handles connection details, script preparation, and execution. - Provides robust error handling and logging for debugging. - Allows configuration of session parameters like session and BTEQ I/O encoding. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:BteqOperator` :param sql: SQL statement(s) to be executed using BTEQ. (templated) :param file_path: Optional path to an existing SQL or BTEQ script file. If provided, this file will be used instead of the `sql` content. This path represents remote file path when executing remotely via SSH, or local file path when executing locally. :param teradata_conn_id: Reference to a specific Teradata connection. :param ssh_conn_id: Optional SSH connection ID for remote execution. Used only when executing scripts remotely. :param remote_working_dir: Temporary directory location on the remote host (via SSH) where the BTEQ script will be transferred and executed. Defaults to `/tmp` if not specified. This is only applicable when `ssh_conn_id` is provided. :param bteq_session_encoding: Character set encoding for the BTEQ session. Defaults to ASCII if not specified. :param bteq_script_encoding: Character encoding for the BTEQ script file. Defaults to ASCII if not specified. :param bteq_quit_rc: Accepts a single integer, list, or tuple of return codes. Specifies which BTEQ return codes should be treated as successful, allowing subsequent tasks to continue execution. :param timeout: Timeout (in seconds) for executing the BTEQ command. Default is 600 seconds (10 minutes). :param timeout_rc: Return code to use if the BTEQ execution fails due to a timeout. To allow DAG execution to continue after a timeout, include this value in `bteq_quit_rc`. If not specified, a timeout will raise an exception and stop the DAG. """ template_fields = "sql" ui_color = "#ff976d" def __init__( self, *, sql: str | None = None, file_path: str | None = None, teradata_conn_id: str = TeradataHook.default_conn_name, ssh_conn_id: str | None = None, remote_working_dir: str | None = None, bteq_session_encoding: str | None = None, bteq_script_encoding: str | None = None, bteq_quit_rc: int | list[int] | tuple[int, ...] | None = None, timeout: int | Literal[600] = 600, # Default to 10 minutes timeout_rc: int | None = None, **kwargs, ) -> None: super().__init__(**kwargs) self.sql = sql self.file_path = file_path self.teradata_conn_id = teradata_conn_id self.ssh_conn_id = ssh_conn_id self.remote_working_dir = remote_working_dir self.timeout = timeout self.timeout_rc = timeout_rc self.bteq_session_encoding = bteq_session_encoding self.bteq_script_encoding = bteq_script_encoding self.bteq_quit_rc = bteq_quit_rc self._hook: BteqHook | None = None self._ssh_hook: SSHHook | None = None self.temp_file_read_encoding = "UTF-8" def execute(self, context: Context) -> int | None: """Execute BTEQ code using the BteqHook.""" if not self.sql and not self.file_path: raise ValueError(Constants.BTEQ_MISSED_PARAMS) self._hook = BteqHook(teradata_conn_id=self.teradata_conn_id, ssh_conn_id=self.ssh_conn_id) self._ssh_hook = SSHHook(ssh_conn_id=self.ssh_conn_id) if self.ssh_conn_id else None # Validate and set BTEQ session and script encoding if not self.bteq_session_encoding or self.bteq_session_encoding == "ASCII": self.bteq_session_encoding = "" if self.bteq_script_encoding == "UTF8": self.temp_file_read_encoding = "UTF-8" elif self.bteq_script_encoding == "UTF16": self.temp_file_read_encoding = "UTF-16" self.bteq_script_encoding = "" elif self.bteq_session_encoding == "UTF8" and ( not self.bteq_script_encoding or self.bteq_script_encoding == "ASCII" ): self.bteq_script_encoding = "UTF8" elif self.bteq_session_encoding == "UTF16": if not self.bteq_script_encoding or self.bteq_script_encoding == "ASCII": self.bteq_script_encoding = "UTF8" # for file reading in python. Mapping BTEQ encoding to Python encoding if self.bteq_script_encoding == "UTF8": self.temp_file_read_encoding = "UTF-8" elif self.bteq_script_encoding == "UTF16": self.temp_file_read_encoding = "UTF-16" # Handling execution on local: if not self._ssh_hook: if self.sql: bteq_script = prepare_bteq_script_for_local_execution( sql=self.sql, ) return self._hook.execute_bteq_script( bteq_script, self.remote_working_dir, self.bteq_script_encoding, self.timeout, self.timeout_rc, self.bteq_session_encoding, self.bteq_quit_rc, self.temp_file_read_encoding, ) if self.file_path: if not is_valid_file(self.file_path): raise ValueError(Constants.BTEQ_INVALID_PATH % self.file_path) try: is_valid_encoding(self.file_path, self.temp_file_read_encoding or "UTF-8") except UnicodeDecodeError as e: errmsg = Constants.BTEQ_INVALID_CHARSET % (self.file_path, "UTF-8") if self.bteq_script_encoding: errmsg = Constants.BTEQ_INVALID_CHARSET % (self.file_path, self.bteq_script_encoding) raise ValueError(errmsg) from e return self._handle_local_bteq_file( file_path=self.file_path, context=context, ) # Execution on Remote machine elif self._ssh_hook: # When sql statement is provided as input through sql parameter, Preparing the bteq script if self.sql: bteq_script = prepare_bteq_script_for_remote_execution( conn=self._hook.get_conn(), sql=self.sql, ) return self._hook.execute_bteq_script( bteq_script, self.remote_working_dir, self.bteq_script_encoding, self.timeout, self.timeout_rc, self.bteq_session_encoding, self.bteq_quit_rc, self.temp_file_read_encoding, ) if self.file_path: with self._ssh_hook.get_conn() as ssh_client: # When .sql or .bteq remote file path is provided as input through file_path parameter, executing on remote machine if self.file_path and is_valid_remote_bteq_script_file(ssh_client, self.file_path): return self._handle_remote_bteq_file( ssh_client=self._ssh_hook.get_conn(), file_path=self.file_path, context=context, ) raise ValueError(Constants.BTEQ_REMOTE_FILE_PATH_INVALID % self.file_path) else: raise ValueError(Constants.BTEQ_MISSED_PARAMS) return None def _handle_remote_bteq_file( self, ssh_client: SSHClient, file_path: str | None, context: Context, ) -> int | None: if file_path: with ssh_client: sftp = ssh_client.open_sftp() try: with sftp.open(file_path, "r") as remote_file: original_content = remote_file.read().decode(self.temp_file_read_encoding or "UTF-8") finally: sftp.close() rendered_content = original_content if contains_template(original_content): rendered_content = self.render_template(original_content, context) if self._hook: bteq_script = prepare_bteq_script_for_remote_execution( conn=self._hook.get_conn(), sql=rendered_content, ) return self._hook.execute_bteq_script_at_remote( bteq_script, self.remote_working_dir, self.bteq_script_encoding, self.timeout, self.timeout_rc, self.bteq_session_encoding, self.bteq_quit_rc, self.temp_file_read_encoding, ) return None raise ValueError(Constants.BTEQ_MISSED_PARAMS) def _handle_local_bteq_file( self, file_path: str, context: Context, ) -> int | None: if file_path and is_valid_file(file_path): file_content = read_file(file_path, encoding=str(self.temp_file_read_encoding or "UTF-8")) # Manually render using operator's context rendered_content = file_content if contains_template(file_content): rendered_content = self.render_template(file_content, context) bteq_script = prepare_bteq_script_for_local_execution( sql=rendered_content, ) if self._hook: result = self._hook.execute_bteq_script( bteq_script, self.remote_working_dir, self.bteq_script_encoding, self.timeout, self.timeout_rc, self.bteq_session_encoding, self.bteq_quit_rc, self.temp_file_read_encoding, ) return result return None def on_kill(self) -> None: """Handle task termination by invoking the on_kill method of BteqHook.""" if self._hook: self._hook.on_kill() else: self.log.warning("BteqHook was not initialized. Nothing to terminate.")
BteqOperator
python
django__django
django/contrib/postgres/indexes.py
{ "start": 6027, "end": 6894 }
class ____(PostgresIndex): suffix = "gist" def __init__(self, *expressions, buffering=None, fillfactor=None, **kwargs): self.buffering = buffering self.fillfactor = fillfactor super().__init__(*expressions, **kwargs) def deconstruct(self): path, args, kwargs = super().deconstruct() if self.buffering is not None: kwargs["buffering"] = self.buffering if self.fillfactor is not None: kwargs["fillfactor"] = self.fillfactor return path, args, kwargs def get_with_params(self): with_params = [] if self.buffering is not None: with_params.append("buffering = %s" % ("on" if self.buffering else "off")) if self.fillfactor is not None: with_params.append("fillfactor = %d" % self.fillfactor) return with_params
GistIndex
python
keras-team__keras
keras/src/ops/math.py
{ "start": 6379, "end": 7727 }
class ____(Operation): def __init__(self, k, *, name=None): super().__init__(name=name) self.k = k def compute_output_spec(self, targets, predictions): return KerasTensor(shape=targets.shape, dtype="bool") def call(self, targets, predictions): return backend.math.in_top_k(targets, predictions, self.k) @keras_export("keras.ops.in_top_k") def in_top_k(targets, predictions, k): """Checks if the targets are in the top-k predictions. Args: targets: A tensor of true labels. predictions: A tensor of predicted labels. k: An integer representing the number of predictions to consider. Returns: A boolean tensor of the same shape as `targets`, where each element indicates whether the corresponding target is in the top-k predictions. Example: >>> targets = keras.ops.convert_to_tensor([2, 5, 3]) >>> predictions = keras.ops.convert_to_tensor( ... [[0.1, 0.4, 0.6, 0.9, 0.5], ... [0.1, 0.7, 0.9, 0.8, 0.3], ... [0.1, 0.6, 0.9, 0.9, 0.5]]) >>> in_top_k(targets, predictions, k=3) array([ True False True], shape=(3,), dtype=bool) """ if any_symbolic_tensors((targets, predictions)): return InTopK(k).symbolic_call(targets, predictions) return backend.math.in_top_k(targets, predictions, k)
InTopK
python
wandb__wandb
wandb/sdk/artifacts/_generated/input_types.py
{ "start": 5395, "end": 5615 }
class ____(GQLInput): aliases: List[ArtifactCollectionAliasInput] artifact_id: GQLId = Field(alias="artifactID") client_mutation_id: Optional[str] = Field(alias="clientMutationId", default=None)
AddAliasesInput
python
aio-libs__aiohttp
aiohttp/helpers.py
{ "start": 27920, "end": 28006 }
class ____(BaseKey[_T]): """Keys for static typing support in Application."""
AppKey
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 932373, "end": 933571 }
class ____(sgqlc.types.Type): """An error in a `CODEOWNERS` file.""" __schema__ = github_schema __field_names__ = ("column", "kind", "line", "message", "path", "source", "suggestion") column = sgqlc.types.Field(sgqlc.types.non_null(Int), graphql_name="column") """The column number where the error occurs.""" kind = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="kind") """A short string describing the type of error.""" line = sgqlc.types.Field(sgqlc.types.non_null(Int), graphql_name="line") """The line number where the error occurs.""" message = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="message") """A complete description of the error, combining information from other fields. """ path = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="path") """The path to the file when the error occurs.""" source = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="source") """The content of the line where the error occurs.""" suggestion = sgqlc.types.Field(String, graphql_name="suggestion") """A suggestion of how to fix the error."""
RepositoryCodeownersError
python
PrefectHQ__prefect
src/prefect/server/utilities/messaging/__init__.py
{ "start": 917, "end": 1295 }
class ____(abc.ABC): @abc.abstractmethod async def clear_recently_seen_messages(self) -> None: ... @abc.abstractmethod async def without_duplicates( self, attribute: str, messages: Iterable[M] ) -> list[M]: ... @abc.abstractmethod async def forget_duplicates( self, attribute: str, messages: Iterable[Message] ) -> None: ...
Cache
python
pytorch__pytorch
torch/__init__.py
{ "start": 71201, "end": 71423 }
class ____(_LegacyStorage): @classproperty def dtype(self): _warn_typed_storage_removal(stacklevel=3) return self._dtype @classproperty def _dtype(self): return torch.long
LongStorage
python
mitmproxy__pdoc
test/testdata/type_stubs/__init__.py
{ "start": 187, "end": 653 }
class ____: attr = 42 """An attribute""" def meth(self, y): """A simple method.""" class Subclass: attr = "42" """An attribute""" def meth(self, y): """A simple method.""" def no_type_annotation(self, z): """A method not present in the .pyi file.""" def overloaded(self, x): """An overloaded method.""" __all__ = [ "func", "var", "Class", "ImportedClass", ]
Class
python
ansible__ansible
lib/ansible/errors/__init__.py
{ "start": 8888, "end": 9301 }
class ____(AnsibleTemplateError): """Raised when processing was requested on an untrusted template or expression.""" _default_message = 'Encountered untrusted template or expression.' _default_help_text = ('Templates and expressions must be defined by trusted sources such as playbooks or roles, ' 'not untrusted sources such as module results.')
TemplateTrustCheckFailedError
python
mlflow__mlflow
tests/store/artifact/test_artifact_repo.py
{ "start": 642, "end": 1075 }
class ____(ArtifactRepository): def log_artifact(self, local_file, artifact_path=None): raise NotImplementedError() def log_artifacts(self, local_dir, artifact_path=None): raise NotImplementedError() def list_artifacts(self, path): raise NotImplementedError() def _download_file(self, remote_file_path, local_path): assert remote_file_path.endswith(_MODEL_FILE)
ArtifactRepositoryImpl
python
mlflow__mlflow
mlflow/genai/labeling/labeling.py
{ "start": 492, "end": 1097 }
class ____: """The agent configuration, used for generating responses in the review app. .. note:: This functionality is only available in Databricks. Please run `pip install mlflow[databricks]` to use it. """ def __init__(self, agent: "_Agent"): self._agent = agent @property def agent_name(self) -> str: """The name of the agent.""" return self._agent.agent_name @property def model_serving_endpoint(self) -> str: """The model serving endpoint used by the agent.""" return self._agent.model_serving_endpoint
Agent
python
spyder-ide__spyder
spyder/utils/syntaxhighlighters.py
{ "start": 5868, "end": 13692 }
class ____(QSyntaxHighlighter): """Base Syntax Highlighter Class""" # Syntax highlighting rules: PROG = None BLANKPROG = re.compile(r"\s+") # Syntax highlighting states (from one text block to another): NORMAL = 0 # Syntax highlighting parameters. BLANK_ALPHA_FACTOR = 0.31 sig_outline_explorer_data_changed = Signal() # Use to signal font change sig_font_changed = Signal() def __init__(self, parent, font=None, color_scheme='Spyder'): QSyntaxHighlighter.__init__(self, parent) self.font = font if isinstance(color_scheme, str): self.color_scheme = get_color_scheme(color_scheme) else: self.color_scheme = color_scheme self.background_color = None self.currentline_color = None self.currentcell_color = None self.occurrence_color = None self.ctrlclick_color = None self.sideareas_color = None self.matched_p_color = None self.unmatched_p_color = None self.formats = None self.setup_formats(font) self.cell_separators = None self.editor = None self.patterns = DEFAULT_COMPILED_PATTERNS # List of cells self._cell_list = [] def get_background_color(self): return QColor(self.background_color) def get_foreground_color(self): """Return foreground ('normal' text) color""" return self.formats["normal"].foreground().color() def get_currentline_color(self): return QColor(self.currentline_color) def get_currentcell_color(self): return QColor(self.currentcell_color) def get_occurrence_color(self): return QColor(self.occurrence_color) def get_ctrlclick_color(self): return QColor(self.ctrlclick_color) def get_sideareas_color(self): return QColor(self.sideareas_color) def get_matched_p_color(self): return QColor(self.matched_p_color) def get_unmatched_p_color(self): return QColor(self.unmatched_p_color) def get_comment_color(self): """ Return color for the comments """ return self.formats['comment'].foreground().color() def get_color_name(self, fmt): """Return color name assigned to a given format""" return self.formats[fmt].foreground().color().name() def setup_formats(self, font=None): base_format = QTextCharFormat() if font is not None: self.font = font if self.font is not None: base_format.setFont(self.font) self.sig_font_changed.emit() self.formats = {} colors = self.color_scheme.copy() self.background_color = colors.pop("background") self.currentline_color = colors.pop("currentline") self.currentcell_color = colors.pop("currentcell") self.occurrence_color = colors.pop("occurrence") self.ctrlclick_color = colors.pop("ctrlclick") self.sideareas_color = colors.pop("sideareas") self.matched_p_color = colors.pop("matched_p") self.unmatched_p_color = colors.pop("unmatched_p") for name, (color, bold, italic) in list(colors.items()): format = QTextCharFormat(base_format) format.setForeground(QColor(color)) if bold: format.setFontWeight(QFont.Bold) format.setFontItalic(italic) self.formats[name] = format def set_color_scheme(self, color_scheme): if isinstance(color_scheme, str): self.color_scheme = get_color_scheme(color_scheme) else: self.color_scheme = color_scheme self.setup_formats() self.rehighlight() @staticmethod def _find_prev_non_blank_block(current_block): previous_block = (current_block.previous() if current_block.blockNumber() else None) # find the previous non-blank block while (previous_block and previous_block.blockNumber() and previous_block.text().strip() == ''): previous_block = previous_block.previous() return previous_block def update_patterns(self, patterns): """Update patterns to underline.""" all_patterns = DEFAULT_PATTERNS.copy() additional_patterns = patterns.copy() # Check that default keys are not overwritten for key in DEFAULT_PATTERNS.keys(): if key in additional_patterns: # TODO: print warning or check this at the plugin level? additional_patterns.pop(key) all_patterns.update(additional_patterns) self.patterns = create_patterns(all_patterns, compile=True) def highlightBlock(self, text): """ Highlights a block of text. Please do not override, this method. Instead you should implement :func:`spyder.utils.syntaxhighplighters.SyntaxHighlighter.highlight_block`. :param text: text to highlight. """ self.highlight_block(text) def highlight_block(self, text): """ Abstract method. Override this to apply syntax highlighting. :param text: Line of text to highlight. :param block: current block """ raise NotImplementedError() def highlight_patterns(self, text, offset=0): """Highlight URI and mailto: patterns.""" for match in self.patterns.finditer(text, offset): for __, value in list(match.groupdict().items()): if value: start, end = get_span(match) start = max([0, start + offset]) end = max([0, end + offset]) font = self.format(start) font.setUnderlineStyle(QTextCharFormat.SingleUnderline) self.setFormat(start, end - start, font) def highlight_spaces(self, text, offset=0): """ Make blank space less apparent by setting the foreground alpha. This only has an effect when 'Show blank space' is turned on. """ flags_text = self.document().defaultTextOption().flags() show_blanks = flags_text & QTextOption.ShowTabsAndSpaces if show_blanks: format_leading = self.formats.get("leading", None) format_trailing = self.formats.get("trailing", None) text = text[offset:] for match in self.BLANKPROG.finditer(text): start, end = get_span(match) start = max([0, start+offset]) end = max([0, end+offset]) # Format trailing spaces at the end of the line. if end == qstring_length(text) and format_trailing is not None: self.setFormat(start, end - start, format_trailing) # Format leading spaces, e.g. indentation. if start == 0 and format_leading is not None: self.setFormat(start, end - start, format_leading) format = self.format(start) color_foreground = format.foreground().color() alpha_new = self.BLANK_ALPHA_FACTOR * color_foreground.alphaF() color_foreground.setAlphaF(alpha_new) self.setFormat(start, end - start, color_foreground) def highlight_extras(self, text, offset=0): """ Perform additional global text highlight. Derived classes could call this function at the end of highlight_block(). """ self.highlight_spaces(text, offset=offset) self.highlight_patterns(text, offset=offset) def rehighlight(self): QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) QSyntaxHighlighter.rehighlight(self) QApplication.restoreOverrideCursor()
BaseSH
python
readthedocs__readthedocs.org
readthedocs/projects/migrations/0022_add-alias-slug.py
{ "start": 149, "end": 656 }
class ____(migrations.Migration): safe = Safe.after_deploy() dependencies = [ ("projects", "0021_add-webhook-deprecation-feature"), ] operations = [ migrations.AlterField( model_name="projectrelationship", name="alias", field=models.SlugField( blank=True, max_length=255, null=True, verbose_name="Alias", db_index=False, ), ), ]
Migration
python
xlwings__xlwings
xlwings/conversion/standard.py
{ "start": 779, "end": 1054 }
class ____: def __init__(self, options): self.expand = options.get("expand", None) def __call__(self, c): if c.range: # auto-expand the range if self.expand: c.range = c.range.expand(self.expand)
ExpandRangeStage
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pyflakes/F401_33/__init__.py
{ "start": 96, "end": 178 }
class ____: def __init__(self) -> None: from F401_33.other import Ham
Spam
python
docker__docker-py
tests/integration/models_swarm_test.py
{ "start": 107, "end": 1620 }
class ____(unittest.TestCase): def setUp(self): helpers.force_leave_swarm(docker.from_env(version=TEST_API_VERSION)) def tearDown(self): helpers.force_leave_swarm(docker.from_env(version=TEST_API_VERSION)) def test_init_update_leave(self): client = docker.from_env(version=TEST_API_VERSION) client.swarm.init( advertise_addr='127.0.0.1', snapshot_interval=5000, listen_addr=helpers.swarm_listen_addr() ) assert client.swarm.attrs['Spec']['Raft']['SnapshotInterval'] == 5000 client.swarm.update(snapshot_interval=10000) assert client.swarm.attrs['Spec']['Raft']['SnapshotInterval'] == 10000 assert client.swarm.id assert client.swarm.leave(force=True) with pytest.raises(docker.errors.APIError) as cm: client.swarm.reload() assert ( cm.value.response.status_code == 406 or cm.value.response.status_code == 503 ) def test_join_on_already_joined_swarm(self): client = docker.from_env(version=TEST_API_VERSION) client.swarm.init() join_token = client.swarm.attrs['JoinTokens']['Manager'] with pytest.raises(docker.errors.APIError) as cm: client.swarm.join( remote_addrs=['127.0.0.1'], join_token=join_token, ) assert cm.value.response.status_code == 503 assert 'This node is already part of a swarm.' in cm.value.explanation
SwarmTest
python
spack__spack
lib/spack/spack/vendor/ruamel/yaml/resolver.py
{ "start": 11958, "end": 15564 }
class ____(BaseResolver): """ contrary to the "normal" resolver, the smart resolver delays loading the pattern matching rules. That way it can decide to load 1.1 rules or the (default) 1.2 rules, that no longer support octal without 0o, sexagesimals and Yes/No/On/Off booleans. """ def __init__(self, version=None, loader=None, loadumper=None): # type: (Optional[VersionType], Any, Any) -> None if loader is None and loadumper is not None: loader = loadumper BaseResolver.__init__(self, loader) self._loader_version = self.get_loader_version(version) self._version_implicit_resolver = {} # type: Dict[Any, Any] def add_version_implicit_resolver(self, version, tag, regexp, first): # type: (VersionType, Any, Any, Any) -> None if first is None: first = [None] impl_resolver = self._version_implicit_resolver.setdefault(version, {}) for ch in first: impl_resolver.setdefault(ch, []).append((tag, regexp)) def get_loader_version(self, version): # type: (Optional[VersionType]) -> Any if version is None or isinstance(version, tuple): return version if isinstance(version, list): return tuple(version) # assume string return tuple(map(int, version.split('.'))) @property def versioned_resolver(self): # type: () -> Any """ select the resolver based on the version we are parsing """ version = self.processing_version if isinstance(version, str): version = tuple(map(int, version.split('.'))) if version not in self._version_implicit_resolver: for x in implicit_resolvers: if version in x[0]: self.add_version_implicit_resolver(version, x[1], x[2], x[3]) return self._version_implicit_resolver[version] def resolve(self, kind, value, implicit): # type: (Any, Any, Any) -> Any if kind is ScalarNode and implicit[0]: if value == "": resolvers = self.versioned_resolver.get("", []) else: resolvers = self.versioned_resolver.get(value[0], []) resolvers += self.versioned_resolver.get(None, []) for tag, regexp in resolvers: if regexp.match(value): return tag implicit = implicit[1] if bool(self.yaml_path_resolvers): exact_paths = self.resolver_exact_paths[-1] if kind in exact_paths: return exact_paths[kind] if None in exact_paths: return exact_paths[None] if kind is ScalarNode: return self.DEFAULT_SCALAR_TAG elif kind is SequenceNode: return self.DEFAULT_SEQUENCE_TAG elif kind is MappingNode: return self.DEFAULT_MAPPING_TAG @property def processing_version(self): # type: () -> Any try: version = self.loadumper._scanner.yaml_version except AttributeError: try: if hasattr(self.loadumper, 'typ'): version = self.loadumper.version else: version = self.loadumper._serializer.use_version # dumping except AttributeError: version = None if version is None: version = self._loader_version if version is None: version = _DEFAULT_YAML_VERSION return version
VersionedResolver
python
pallets__werkzeug
tests/test_datastructures.py
{ "start": 19178, "end": 25952 }
class ____: storage_class = ds.Headers def test_basic_interface(self): headers = self.storage_class() headers.add("Content-Type", "text/plain") headers.add("X-Foo", "bar") assert "x-Foo" in headers assert "Content-type" in headers with pytest.raises(ValueError): headers.add("X-Example", "foo\r\n bar") headers["Content-Type"] = "foo/bar" assert headers["Content-Type"] == "foo/bar" assert len(headers.getlist("Content-Type")) == 1 # list conversion assert headers.to_wsgi_list() == [("Content-Type", "foo/bar"), ("X-Foo", "bar")] assert str(headers) == "Content-Type: foo/bar\r\nX-Foo: bar\r\n\r\n" assert str(self.storage_class()) == "\r\n" # extended add headers.add("Content-Disposition", "attachment", filename="foo") assert headers["Content-Disposition"] == "attachment; filename=foo" headers.add("x", "y", z='"') assert headers["x"] == r'y; z="\""' # string conversion headers.add("a", 1) assert headers["a"] == "1" def test_defaults_and_conversion(self): # defaults headers = self.storage_class( [ ("Content-Type", "text/plain"), ("X-Foo", "bar"), ("X-Bar", "1"), ("X-Bar", "2"), ] ) assert headers.getlist("x-bar") == ["1", "2"] assert headers.get("x-Bar") == "1" assert headers.get("Content-Type") == "text/plain" assert headers.setdefault("X-Foo", "nope") == "bar" assert headers.setdefault("X-Bar", "nope") == "1" assert headers.setdefault("X-Baz", "quux") == "quux" assert headers.setdefault("X-Baz", "nope") == "quux" headers.pop("X-Baz") # newlines are not allowed in values with pytest.raises(ValueError): self.storage_class([("X-Example", "foo\r\n bar")]) # type conversion assert headers.get("x-bar", type=int) == 1 assert headers.getlist("x-bar", type=int) == [1, 2] # list like operations assert headers[0] == ("Content-Type", "text/plain") assert headers[:1] == self.storage_class([("Content-Type", "text/plain")]) del headers[:2] del headers[-1] assert headers == self.storage_class([("X-Bar", "1")]) def test_copying(self): a = self.storage_class([("foo", "bar")]) b = a.copy() a.add("foo", "baz") assert a.getlist("foo") == ["bar", "baz"] assert b.getlist("foo") == ["bar"] def test_popping(self): headers = self.storage_class([("a", 1)]) # headers object expect string values. If a non string value # is passed, it tries converting it to a string assert headers.pop("a") == "1" assert headers.pop("b", "2") == "2" with pytest.raises(KeyError): headers.pop("c") def test_set_arguments(self): a = self.storage_class() a.set("Content-Disposition", "useless") a.set("Content-Disposition", "attachment", filename="foo") assert a["Content-Disposition"] == "attachment; filename=foo" def test_reject_newlines(self): h = self.storage_class() for variation in "foo\nbar", "foo\r\nbar", "foo\rbar": with pytest.raises(ValueError): h["foo"] = variation with pytest.raises(ValueError): h.add("foo", variation) with pytest.raises(ValueError): h.add("foo", "test", option=variation) with pytest.raises(ValueError): h.set("foo", variation) with pytest.raises(ValueError): h.set("foo", "test", option=variation) def test_slicing(self): # there's nothing wrong with these being native strings # Headers doesn't care about the data types h = self.storage_class() h.set("X-Foo-Poo", "bleh") h.set("Content-Type", "application/whocares") h.set("X-Forwarded-For", "192.168.0.123") h[:] = [(k, v) for k, v in h if k.startswith("X-")] assert list(h) == [("X-Foo-Poo", "bleh"), ("X-Forwarded-For", "192.168.0.123")] def test_extend(self): h = self.storage_class([("a", "0"), ("b", "1"), ("c", "2")]) h.extend(ds.Headers([("a", "3"), ("a", "4")])) assert h.getlist("a") == ["0", "3", "4"] h.extend(b=["5", "6"]) assert h.getlist("b") == ["1", "5", "6"] h.extend({"c": "7", "d": ["8", "9"]}, c="10") assert h.getlist("c") == ["2", "7", "10"] assert h.getlist("d") == ["8", "9"] with pytest.raises(TypeError): h.extend({"x": "x"}, {"x": "x"}) def test_update(self): h = self.storage_class([("a", "0"), ("b", "1"), ("c", "2")]) h.update(ds.Headers([("a", "3"), ("a", "4")])) assert h.getlist("a") == ["3", "4"] h.update(b=["5", "6"]) assert h.getlist("b") == ["5", "6"] h.update({"c": "7", "d": ["8", "9"]}) assert h.getlist("c") == ["7"] assert h.getlist("d") == ["8", "9"] h.update({"c": "10"}, c="11") assert h.getlist("c") == ["11"] with pytest.raises(TypeError): h.extend({"x": "x"}, {"x": "x"}) def test_setlist(self): h = self.storage_class([("a", "0"), ("b", "1"), ("c", "2")]) h.setlist("b", ["3", "4"]) assert h[1] == ("b", "3") assert h[-1] == ("b", "4") h.setlist("b", []) assert "b" not in h h.setlist("d", ["5"]) assert h["d"] == "5" def test_setlistdefault(self): h = self.storage_class([("a", "0"), ("b", "1"), ("c", "2")]) assert h.setlistdefault("a", ["3"]) == ["0"] assert h.setlistdefault("d", ["4", "5"]) == ["4", "5"] def test_to_wsgi_list(self): h = self.storage_class() h.set("Key", "Value") for key, value in h.to_wsgi_list(): assert key == "Key" assert value == "Value" def test_equality(self): # test equality, given keys are case insensitive h1 = self.storage_class() h1.add("X-Foo", "foo") h1.add("X-Bar", "bah") h1.add("X-Bar", "humbug") h2 = self.storage_class() h2.add("x-foo", "foo") h2.add("x-bar", "bah") h2.add("x-bar", "humbug") assert h1 == h2 def test_or(self) -> None: a = ds.Headers({"x": 1}) b = a | {"y": 2} assert isinstance(b, ds.Headers) assert "x" in b and "y" in b def test_ior(self) -> None: a = ds.Headers({"x": 1}) a |= {"y": 2} assert "x" in a and "y" in a
TestHeaders
python
scipy__scipy
benchmarks/benchmarks/go_benchmark_functions/go_funcs_E.py
{ "start": 6324, "end": 7476 }
class ____(Benchmark): r""" El-Attar-Vidyasagar-Dutta [1]_ objective function. This class defines the El-Attar-Vidyasagar-Dutta function global optimization problem. This is a multimodal minimization problem defined as follows: .. math:: f_{\text{ElAttarVidyasagarDutta}}(x) = (x_1^2 + x_2 - 10)^2 + (x_1 + x_2^2 - 7)^2 + (x_1^2 + x_2^3 - 1)^2 with :math:`x_i \in [-100, 100]` for :math:`i = 1, 2`. *Global optimum*: :math:`f(x) = 1.712780354` for :math:`x= [3.40918683, -2.17143304]` .. [1] Gavana, A. Global Optimization Benchmarks and AMPGO retrieved 2015 """ def __init__(self, dimensions=2): Benchmark.__init__(self, dimensions) self._bounds = list(zip([-100.0] * self.N, [100.0] * self.N)) self.custom_bounds = [(-4, 4), (-4, 4)] self.global_optimum = [[3.40918683, -2.17143304]] self.fglob = 1.712780354 def fun(self, x, *args): self.nfev += 1 return ((x[0] ** 2 + x[1] - 10) ** 2 + (x[0] + x[1] ** 2 - 7) ** 2 + (x[0] ** 2 + x[1] ** 3 - 1) ** 2)
ElAttarVidyasagarDutta
python
matplotlib__matplotlib
lib/matplotlib/tests/test_mlab.py
{ "start": 39876, "end": 42695 }
class ____: def test_evaluate_diff_dim(self): """ Test the evaluate method when the dim's of dataset and points have different dimensions. """ x1 = np.arange(3, 10, 2) kde = mlab.GaussianKDE(x1) x2 = np.arange(3, 12, 2) y_expected = [ 0.08797252, 0.11774109, 0.11774109, 0.08797252, 0.0370153 ] y = kde.evaluate(x2) np.testing.assert_array_almost_equal(y, y_expected, 7) def test_evaluate_inv_dim(self): """ Invert the dimensions; i.e., for a dataset of dimension 1 [3, 2, 4], the points should have a dimension of 3 [[3], [2], [4]]. """ np.random.seed(8765678) n_basesample = 50 multidim_data = np.random.randn(n_basesample) kde = mlab.GaussianKDE(multidim_data) x2 = [[1], [2], [3]] with pytest.raises(ValueError): kde.evaluate(x2) def test_evaluate_dim_and_num(self): """Tests if evaluated against a one by one array""" x1 = np.arange(3, 10, 2) x2 = np.array([3]) kde = mlab.GaussianKDE(x1) y_expected = [0.08797252] y = kde.evaluate(x2) np.testing.assert_array_almost_equal(y, y_expected, 7) def test_evaluate_point_dim_not_one(self): x1 = np.arange(3, 10, 2) x2 = [np.arange(3, 10, 2), np.arange(3, 10, 2)] kde = mlab.GaussianKDE(x1) with pytest.raises(ValueError): kde.evaluate(x2) def test_evaluate_equal_dim_and_num_lt(self): x1 = np.arange(3, 10, 2) x2 = np.arange(3, 8, 2) kde = mlab.GaussianKDE(x1) y_expected = [0.08797252, 0.11774109, 0.11774109] y = kde.evaluate(x2) np.testing.assert_array_almost_equal(y, y_expected, 7) def test_psd_onesided_norm(): u = np.array([0, 1, 2, 3, 1, 2, 1]) dt = 1.0 Su = np.abs(np.fft.fft(u) * dt)**2 / (dt * u.size) P, f = mlab.psd(u, NFFT=u.size, Fs=1/dt, window=mlab.window_none, detrend=mlab.detrend_none, noverlap=0, pad_to=None, scale_by_freq=None, sides='onesided') Su_1side = np.append([Su[0]], Su[1:4] + Su[4:][::-1]) assert_allclose(P, Su_1side, atol=1e-06) def test_psd_oversampling(): """Test the case len(x) < NFFT for psd().""" u = np.array([0, 1, 2, 3, 1, 2, 1]) dt = 1.0 Su = np.abs(np.fft.fft(u) * dt)**2 / (dt * u.size) P, f = mlab.psd(u, NFFT=u.size*2, Fs=1/dt, window=mlab.window_none, detrend=mlab.detrend_none, noverlap=0, pad_to=None, scale_by_freq=None, sides='onesided') Su_1side = np.append([Su[0]], Su[1:4] + Su[4:][::-1]) assert_almost_equal(np.sum(P), np.sum(Su_1side)) # same energy
TestGaussianKDEEvaluate
python
sphinx-doc__sphinx
sphinx/ext/autodoc/_dynamic/_mock.py
{ "start": 3239, "end": 3720 }
class ____(Loader): """A loader for mocking.""" def __init__(self, finder: MockFinder) -> None: super().__init__() self.finder = finder def create_module(self, spec: ModuleSpec) -> ModuleType: logger.debug('[autodoc] adding a mock module as %s!', spec.name) self.finder.mocked_modules.append(spec.name) return _MockModule(spec.name) def exec_module(self, module: ModuleType) -> None: pass # nothing to do
MockLoader
python
walkccc__LeetCode
solutions/2295. Replace Elements in an Array/2295.py
{ "start": 0, "end": 369 }
class ____: def arrayChange( self, nums: list[int], operations: list[list[int]], ) -> list[int]: numToIndex = {num: i for i, num in enumerate(nums)} for original, replaced in operations: index = numToIndex[original] nums[index] = replaced del numToIndex[original] numToIndex[replaced] = index return nums
Solution
python
openai__openai-python
src/openai/types/fine_tuning/dpo_method_param.py
{ "start": 259, "end": 414 }
class ____(TypedDict, total=False): hyperparameters: DpoHyperparametersParam """The hyperparameters used for the DPO fine-tuning job."""
DpoMethodParam
python
dask__dask
dask/dataframe/io/parquet/arrow.py
{ "start": 5297, "end": 13604 }
class ____: """Simple class providing a `name` and `keys` attribute for a single partition column. This class was originally designed as a mechanism to build a duck-typed version of pyarrow's deprecated `ParquetPartitions` class. Now that `ArrowLegacyEngine` is deprecated, this class can be modified/removed, but it is still used as a convenience. """ def __init__(self, name, keys): self.name = name self.keys = pd.Index(keys.sort_values(), copy=False) def __dask_tokenize__(self): return tokenize(self.name, self.keys) def _frag_subset(old_frag, row_groups): """Create new fragment with row-group subset.""" return old_frag.format.make_fragment( old_frag.path, old_frag.filesystem, old_frag.partition_expression, row_groups=row_groups, ) def _get_pandas_metadata(schema): """Get pandas-specific metadata from schema.""" has_pandas_metadata = schema.metadata is not None and b"pandas" in schema.metadata if has_pandas_metadata: return json.loads(schema.metadata[b"pandas"].decode("utf8")) else: return {} def _read_table_from_path( path, fs, row_groups, columns, schema, filters, **kwargs, ): """Read arrow table from file path. Used by `ArrowDatasetEngine._read_table` when no filters are specified (otherwise fragments are converted directly into tables). """ # Define file-opening options read_kwargs = kwargs.get("read", {}).copy() precache_options, open_file_options = _process_open_file_options( read_kwargs.pop("open_file_options", {}), **( { "allow_precache": False, "default_cache": "none", } if _is_local_fs(fs) else { "columns": columns, "row_groups": row_groups if row_groups == [None] else [row_groups], "default_engine": "pyarrow", "default_cache": "none", } ), ) # Use `pre_buffer=True` if the option is supported and an optimized # "pre-caching" method isn't already specified in `precache_options` # (The distinct fsspec and pyarrow optimizations will conflict) pre_buffer_default = precache_options.get("method", None) is None pre_buffer = {"pre_buffer": read_kwargs.pop("pre_buffer", pre_buffer_default)} with _open_input_files( [path], fs=fs, precache_options=precache_options, **open_file_options, )[0] as fil: if row_groups == [None]: return pq.ParquetFile(fil, **pre_buffer).read( columns=columns, use_threads=False, use_pandas_metadata=True, **read_kwargs, ) else: return pq.ParquetFile(fil, **pre_buffer).read_row_groups( row_groups, columns=columns, use_threads=False, use_pandas_metadata=True, **read_kwargs, ) def _get_rg_statistics(row_group, col_names): """Custom version of pyarrow's RowGroupInfo.statistics method (https://github.com/apache/arrow/blob/master/python/pyarrow/_dataset.pyx) We use column names to specify the specific subset of columns that we need statistics for. This is more optimal than the upstream `RowGroupInfo.statistics` method, which will return statistics for all columns. """ row_group_schema = dict( zip( row_group.schema.names, itertools.accumulate( [ # Need to account for multi-field struct columns max(row_group.schema.types[i].num_fields, 1) for i in range(len(row_group.schema.names) - 1) ], initial=0, ), ) ) def name_stats(column_name): col = row_group.metadata.column(row_group_schema[column_name]) stats = col.statistics if stats is None or not stats.has_min_max: return None, None name = col.path_in_schema field_index = row_group.schema.get_field_index(name) if field_index < 0: return None, None return col.path_in_schema, { "min": stats.min, "max": stats.max, "null_count": stats.null_count, } return { name: stats for name, stats in map(name_stats, col_names) if stats is not None } def _need_filtering(filters, partition_keys): # Check if we need to generate a fragment for filtering. # We only need to do this if we are applying filters to # columns that were not already filtered by "partition". partition_cols = ( {v[0] for v in flatten(partition_keys, container=list) if len(v)} if partition_keys else set() ) filtered_cols = ( {v[0] for v in flatten(filters, container=list) if len(v)} if filters else set() ) return bool(filtered_cols - partition_cols) def _hive_dirname(name, val): # Simple utility to produce hive directory name. # Note that "__HIVE_DEFAULT_PARTITION__" is the # conventional "null" label in other platforms val = "__HIVE_DEFAULT_PARTITION__" if pd.isna(val) else val return f"{name}={val}" def _process_kwargs(partitioning=None, **kwargs): # Pre-process a dict of `pyarrow.dataset.dataset`` key-word # arguments. Primary purpose is to convert a dictionary-based # "partitioning" option into a proper `Partitioning` object return { "partitioning": ( pa_ds.partitioning(**partitioning) if isinstance(partitioning, dict) else partitioning ), **kwargs, } def _filters_to_expression(filters, propagate_null=False, nan_is_null=True): # Mostly copied from: pq.filters_to_expression # TODO: Use pq.filters_to_expression if/when null-value # handling is resolved. # See: https://github.com/dask/dask/issues/9845 if isinstance(filters, pa_ds.Expression): return filters if filters is not None: if len(filters) == 0 or any(len(f) == 0 for f in filters): raise ValueError("Malformed filters") if isinstance(filters[0][0], str): # We have encountered the situation where we have one nesting level # too few: # We have [(,,), ..] instead of [[(,,), ..]] filters = [filters] def convert_single_predicate(col, op, val): field = pa_ds.field(col) # Handle null-value comparison if val is None or (nan_is_null and val is np.nan): if op == "is": return field.is_null(nan_is_null=nan_is_null) elif op == "is not": return ~field.is_null(nan_is_null=nan_is_null) else: raise ValueError( f'"{(col, op, val)}" is not a supported predicate ' f'Please use "is" or "is not" for null comparison.' ) if op == "=" or op == "==": expr = field == val elif op == "!=": expr = field != val elif op == "<": expr = field < val elif op == ">": expr = field > val elif op == "<=": expr = field <= val elif op == ">=": expr = field >= val elif op == "in": expr = field.isin(val) elif op == "not in": expr = ~field.isin(val) else: raise ValueError( f'"{(col, op, val)}" is not a valid operator in predicates.' ) # (Optionally) Avoid null-value propagation if not propagate_null and op in ("!=", "not in"): return field.is_null(nan_is_null=nan_is_null) | expr return expr disjunction_members = [] for conjunction in filters: conjunction_members = [ convert_single_predicate(col, op, val) for col, op, val in conjunction ] disjunction_members.append(reduce(operator.and_, conjunction_members)) return reduce(operator.or_, disjunction_members) # # ArrowDatasetEngine #
PartitionObj
python
huggingface__transformers
src/transformers/models/qwen2_5_omni/modular_qwen2_5_omni.py
{ "start": 94804, "end": 95175 }
class ____(Qwen2_5_VLTextModel): config: Qwen2_5OmniTextConfig _no_split_modules = ["Qwen2_5OmniDecoderLayer"] def __init__(self, config: Qwen2_5OmniTextConfig): super().__init__(config) @auto_docstring( custom_intro=""" The Qwen2.5OmniThinker model which consists of a audio backbone and a language model. """ )
Qwen2_5OmniThinkerTextModel
python
huggingface__transformers
src/transformers/models/bridgetower/modeling_bridgetower.py
{ "start": 16852, "end": 17557 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.intermediate_size, config.hidden_size) self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) self.dropout = nn.Dropout(config.hidden_dropout_prob) def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor: hidden_states = self.dense(hidden_states) hidden_states = self.dropout(hidden_states) hidden_states = self.LayerNorm(hidden_states + input_tensor) return hidden_states # Copied from transformers.models.bert.modeling_bert.BertPooler with Bert->BridgeTower
BridgeTowerOutput
python
pallets__jinja
tests/test_core_tags.py
{ "start": 15779, "end": 19913 }
class ____: def test_normal(self, env_trim): tmpl = env_trim.from_string("{% set foo = 1 %}{{ foo }}") assert tmpl.render() == "1" assert tmpl.module.foo == 1 def test_block(self, env_trim): tmpl = env_trim.from_string("{% set foo %}42{% endset %}{{ foo }}") assert tmpl.render() == "42" assert tmpl.module.foo == "42" def test_block_escaping(self): env = Environment(autoescape=True) tmpl = env.from_string( "{% set foo %}<em>{{ test }}</em>{% endset %}foo: {{ foo }}" ) assert tmpl.render(test="<unsafe>") == "foo: <em>&lt;unsafe&gt;</em>" def test_set_invalid(self, env_trim): pytest.raises( TemplateSyntaxError, env_trim.from_string, "{% set foo['bar'] = 1 %}" ) tmpl = env_trim.from_string("{% set foo.bar = 1 %}") exc_info = pytest.raises(TemplateRuntimeError, tmpl.render, foo={}) assert "non-namespace object" in exc_info.value.message def test_namespace_redefined(self, env_trim): tmpl = env_trim.from_string("{% set ns = namespace() %}{% set ns.bar = 'hi' %}") exc_info = pytest.raises(TemplateRuntimeError, tmpl.render, namespace=dict) assert "non-namespace object" in exc_info.value.message def test_namespace(self, env_trim): tmpl = env_trim.from_string( "{% set ns = namespace() %}{% set ns.bar = '42' %}{{ ns.bar }}" ) assert tmpl.render() == "42" def test_namespace_block(self, env_trim): tmpl = env_trim.from_string( "{% set ns = namespace() %}{% set ns.bar %}42{% endset %}{{ ns.bar }}" ) assert tmpl.render() == "42" def test_init_namespace(self, env_trim): tmpl = env_trim.from_string( "{% set ns = namespace(d, self=37) %}" "{% set ns.b = 42 %}" "{{ ns.a }}|{{ ns.self }}|{{ ns.b }}" ) assert tmpl.render(d={"a": 13}) == "13|37|42" def test_namespace_loop(self, env_trim): tmpl = env_trim.from_string( "{% set ns = namespace(found=false) %}" "{% for x in range(4) %}" "{% if x == v %}" "{% set ns.found = true %}" "{% endif %}" "{% endfor %}" "{{ ns.found }}" ) assert tmpl.render(v=3) == "True" assert tmpl.render(v=4) == "False" def test_namespace_macro(self, env_trim): tmpl = env_trim.from_string( "{% set ns = namespace() %}" "{% set ns.a = 13 %}" "{% macro magic(x) %}" "{% set x.b = 37 %}" "{% endmacro %}" "{{ magic(ns) }}" "{{ ns.a }}|{{ ns.b }}" ) assert tmpl.render() == "13|37" def test_namespace_set_tuple(self, env_trim): tmpl = env_trim.from_string( "{% set ns = namespace(a=12, b=36) %}" "{% set ns.a, ns.b = ns.a + 1, ns.b + 1 %}" "{{ ns.a }}|{{ ns.b }}" ) assert tmpl.render() == "13|37" def test_block_escaping_filtered(self): env = Environment(autoescape=True) tmpl = env.from_string( "{% set foo | trim %}<em>{{ test }}</em> {% endset %}foo: {{ foo }}" ) assert tmpl.render(test="<unsafe>") == "foo: <em>&lt;unsafe&gt;</em>" def test_block_filtered(self, env_trim): tmpl = env_trim.from_string( "{% set foo | trim | length | string %} 42 {% endset %}{{ foo }}" ) assert tmpl.render() == "2" assert tmpl.module.foo == "2" def test_block_filtered_set(self, env_trim): def _myfilter(val, arg): assert arg == " xxx " return val env_trim.filters["myfilter"] = _myfilter tmpl = env_trim.from_string( '{% set a = " xxx " %}' "{% set foo | myfilter(a) | trim | length | string %}" ' {% set b = " yy " %} 42 {{ a }}{{ b }} ' "{% endset %}" "{{ foo }}" ) assert tmpl.render() == "11" assert tmpl.module.foo == "11"
TestSet
python
sympy__sympy
sympy/polys/polytools.py
{ "start": 211950, "end": 223643 }
class ____(Basic): """Represents a reduced Groebner basis. """ def __new__(cls, F, *gens, **args): """Compute a reduced Groebner basis for a system of polynomials. """ options.allowed_flags(args, ['polys', 'method']) try: polys, opt = parallel_poly_from_expr(F, *gens, **args) except PolificationFailed as exc: raise ComputationFailed('groebner', len(F), exc) from sympy.polys.rings import PolyRing ring = PolyRing(opt.gens, opt.domain, opt.order) polys = [ring.from_dict(poly.rep.to_dict()) for poly in polys if poly] G = _groebner(polys, ring, method=opt.method) G = [Poly._from_dict(g, opt) for g in G] return cls._new(G, opt) @classmethod def _new(cls, basis, options): obj = Basic.__new__(cls) obj._basis = tuple(basis) obj._options = options return obj @property def args(self): basis = (p.as_expr() for p in self._basis) return (Tuple(*basis), Tuple(*self._options.gens)) @property def exprs(self): return [poly.as_expr() for poly in self._basis] @property def polys(self): return list(self._basis) @property def gens(self): return self._options.gens @property def domain(self): return self._options.domain @property def order(self): return self._options.order def __len__(self): return len(self._basis) def __iter__(self): if self._options.polys: return iter(self.polys) else: return iter(self.exprs) def __getitem__(self, item): if self._options.polys: basis = self.polys else: basis = self.exprs return basis[item] def __hash__(self): return hash((self._basis, tuple(self._options.items()))) def __eq__(self, other): if isinstance(other, self.__class__): return self._basis == other._basis and self._options == other._options elif iterable(other): return self.polys == list(other) or self.exprs == list(other) else: return False def __ne__(self, other): return not self == other @property def is_zero_dimensional(self): """ Checks if the ideal generated by a Groebner basis is zero-dimensional. The algorithm checks if the set of monomials not divisible by the leading monomial of any element of ``F`` is bounded. References ========== David A. Cox, John B. Little, Donal O'Shea. Ideals, Varieties and Algorithms, 3rd edition, p. 230 """ def single_var(monomial): return sum(map(bool, monomial)) == 1 exponents = Monomial([0]*len(self.gens)) order = self._options.order for poly in self.polys: monomial = poly.LM(order=order) if single_var(monomial): exponents *= monomial # If any element of the exponents vector is zero, then there's # a variable for which there's no degree bound and the ideal # generated by this Groebner basis isn't zero-dimensional. return all(exponents) def fglm(self, order): """ Convert a Groebner basis from one ordering to another. The FGLM algorithm converts reduced Groebner bases of zero-dimensional ideals from one ordering to another. This method is often used when it is infeasible to compute a Groebner basis with respect to a particular ordering directly. Examples ======== >>> from sympy.abc import x, y >>> from sympy import groebner >>> F = [x**2 - 3*y - x + 1, y**2 - 2*x + y - 1] >>> G = groebner(F, x, y, order='grlex') >>> list(G.fglm('lex')) [2*x - y**2 - y + 1, y**4 + 2*y**3 - 3*y**2 - 16*y + 7] >>> list(groebner(F, x, y, order='lex')) [2*x - y**2 - y + 1, y**4 + 2*y**3 - 3*y**2 - 16*y + 7] References ========== .. [1] J.C. Faugere, P. Gianni, D. Lazard, T. Mora (1994). Efficient Computation of Zero-dimensional Groebner Bases by Change of Ordering """ opt = self._options src_order = opt.order dst_order = monomial_key(order) if src_order == dst_order: return self if not self.is_zero_dimensional: raise NotImplementedError("Cannot convert Groebner bases of ideals with positive dimension") polys = list(self._basis) domain = opt.domain opt = opt.clone({ "domain": domain.get_field(), "order": dst_order, }) from sympy.polys.rings import xring _ring, _ = xring(opt.gens, opt.domain, src_order) for i, poly in enumerate(polys): poly = poly.set_domain(opt.domain).rep.to_dict() polys[i] = _ring.from_dict(poly) G = matrix_fglm(polys, _ring, dst_order) G = [Poly._from_dict(dict(g), opt) for g in G] if not domain.is_Field: G = [g.clear_denoms(convert=True)[1] for g in G] opt.domain = domain return self._new(G, opt) def reduce(self, expr, auto=True): """ Reduces a polynomial modulo a Groebner basis. Given a polynomial ``f`` and a set of polynomials ``G = (g_1, ..., g_n)``, computes a set of quotients ``q = (q_1, ..., q_n)`` and the remainder ``r`` such that ``f = q_1*f_1 + ... + q_n*f_n + r``, where ``r`` vanishes or ``r`` is a completely reduced polynomial with respect to ``G``. Examples ======== >>> from sympy import groebner, expand, Poly >>> from sympy.abc import x, y >>> f = 2*x**4 - x**2 + y**3 + y**2 >>> G = groebner([x**3 - x, y**3 - y]) >>> G.reduce(f) ([2*x, 1], x**2 + y**2 + y) >>> Q, r = _ >>> expand(sum(q*g for q, g in zip(Q, G)) + r) 2*x**4 - x**2 + y**3 + y**2 >>> _ == f True # Using Poly input >>> f_poly = Poly(f, x, y) >>> G = groebner([Poly(x**3 - x), Poly(y**3 - y)]) >>> G.reduce(f_poly) ([Poly(2*x, x, y, domain='ZZ'), Poly(1, x, y, domain='ZZ')], Poly(x**2 + y**2 + y, x, y, domain='ZZ')) """ if isinstance(expr, Poly): if expr.gens != self._options.gens: raise ValueError("Polynomial generators don't match Groebner basis generators") poly = expr.set_domain(self._options.domain) else: poly = Poly._from_expr(expr, self._options) polys = [poly] + list(self._basis) opt = self._options domain = opt.domain retract = False if auto and domain.is_Ring and not domain.is_Field: opt = opt.clone({"domain": domain.get_field()}) retract = True from sympy.polys.rings import xring _ring, _ = xring(opt.gens, opt.domain, opt.order) for i, poly in enumerate(polys): poly = poly.set_domain(opt.domain).rep.to_dict() polys[i] = _ring.from_dict(poly) Q, r = polys[0].div(polys[1:]) Q = [Poly._from_dict(dict(q), opt) for q in Q] r = Poly._from_dict(dict(r), opt) if retract: try: _Q, _r = [q.to_ring() for q in Q], r.to_ring() except CoercionFailed: pass else: Q, r = _Q, _r if not opt.polys: return [q.as_expr() for q in Q], r.as_expr() else: return Q, r def contains(self, poly): """ Check if ``poly`` belongs the ideal generated by ``self``. Examples ======== >>> from sympy import groebner >>> from sympy.abc import x, y >>> f = 2*x**3 + y**3 + 3*y >>> G = groebner([x**2 + y**2 - 1, x*y - 2]) >>> G.contains(f) True >>> G.contains(f + 1) False """ return self.reduce(poly)[1] == 0 @public def poly(expr, *gens, **args): """ Efficiently transform an expression into a polynomial. Examples ======== >>> from sympy import poly >>> from sympy.abc import x >>> poly(x*(x**2 + x - 1)**2) Poly(x**5 + 2*x**4 - x**3 - 2*x**2 + x, x, domain='ZZ') """ options.allowed_flags(args, []) def _poly(expr, opt): terms, poly_terms = [], [] for term in Add.make_args(expr): factors, poly_factors = [], [] for factor in Mul.make_args(term): if factor.is_Add: poly_factors.append(_poly(factor, opt)) elif factor.is_Pow and factor.base.is_Add and \ factor.exp.is_Integer and factor.exp >= 0: poly_factors.append( _poly(factor.base, opt).pow(factor.exp)) else: factors.append(factor) if not poly_factors: terms.append(term) else: product = poly_factors[0] for factor in poly_factors[1:]: product = product.mul(factor) if factors: factor = Mul(*factors) if factor.is_Number: product *= factor else: product = product.mul(Poly._from_expr(factor, opt)) poly_terms.append(product) if not poly_terms: result = Poly._from_expr(expr, opt) else: result = poly_terms[0] for term in poly_terms[1:]: result = result.add(term) if terms: term = Add(*terms) if term.is_Number: result += term else: result = result.add(Poly._from_expr(term, opt)) return result.reorder(*opt.get('gens', ()), **args) expr = sympify(expr) if expr.is_Poly: return Poly(expr, *gens, **args) if 'expand' not in args: args['expand'] = False opt = options.build_options(gens, args) return _poly(expr, opt) def named_poly(n, f, K, name, x, polys): r"""Common interface to the low-level polynomial generating functions in orthopolys and appellseqs. Parameters ========== n : int Index of the polynomial, which may or may not equal its degree. f : callable Low-level generating function to use. K : Domain or None Domain in which to perform the computations. If None, use the smallest field containing the rationals and the extra parameters of x (see below). name : str Name of an arbitrary individual polynomial in the sequence generated by f, only used in the error message for invalid n. x : seq The first element of this argument is the main variable of all polynomials in this sequence. Any further elements are extra parameters required by f. polys : bool, optional If True, return a Poly, otherwise (default) return an expression. """ if n < 0: raise ValueError("Cannot generate %s of index %s" % (name, n)) head, tail = x[0], x[1:] if K is None: K, tail = construct_domain(tail, field=True) poly = DMP(f(int(n), *tail, K), K) if head is None: poly = PurePoly.new(poly, Dummy('x')) else: poly = Poly.new(poly, head) return poly if polys else poly.as_expr()
GroebnerBasis
python
simonw__sqlite-utils
sqlite_utils/utils.py
{ "start": 12403, "end": 13692 }
class ____: def __init__(self): self.couldbe = {key: getattr(self, "test_" + key) for key in self.get_tests()} @classmethod def get_tests(cls): return [ key.split("test_")[-1] for key in cls.__dict__.keys() if key.startswith("test_") ] def test_integer(self, value): try: int(value) return True except (ValueError, TypeError): return False def test_float(self, value): try: float(value) return True except (ValueError, TypeError): return False def __repr__(self) -> str: return self.guessed_type + ": possibilities = " + repr(self.couldbe) @property def guessed_type(self): options = set(self.couldbe.keys()) # Return based on precedence for key in self.get_tests(): if key in options: return key return "text" def evaluate(self, value): if not value or not self.couldbe: return not_these = [] for name, test in self.couldbe.items(): if not test(value): not_these.append(name) for key in not_these: del self.couldbe[key]
ValueTracker
python
tensorflow__tensorflow
tensorflow/python/framework/composite_tensor_gradient.py
{ "start": 3322, "end": 3489 }
class ____(Protocol): """Protocol for adding gradient support to CompositeTensors.""" __composite_gradient__: CompositeTensorGradient
CompositeTensorGradientProtocol
python
bottlepy__bottle
bottle.py
{ "start": 134966, "end": 135656 }
class ____(ServerAdapter): def run(self, handler): # pragma: no cover from cheroot import wsgi from cheroot.ssl import builtin self.options['bind_addr'] = (self.host, self.port) self.options['wsgi_app'] = handler certfile = self.options.pop('certfile', None) keyfile = self.options.pop('keyfile', None) chainfile = self.options.pop('chainfile', None) server = wsgi.Server(**self.options) if certfile and keyfile: server.ssl_adapter = builtin.BuiltinSSLAdapter( certfile, keyfile, chainfile) try: server.start() finally: server.stop()
CherootServer
python
scipy__scipy
scipy/linalg/tests/test_decomp.py
{ "start": 39898, "end": 48554 }
class ____: lapack_driver = 'gesdd' def test_degenerate(self): assert_raises(TypeError, svd, [[1.]], lapack_driver=1.) assert_raises(ValueError, svd, [[1.]], lapack_driver='foo') def test_simple(self): a = [[1, 2, 3], [1, 20, 3], [2, 5, 6]] for full_matrices in (True, False): u, s, vh = svd(a, full_matrices=full_matrices, lapack_driver=self.lapack_driver) assert_array_almost_equal(u.T @ u, eye(3)) assert_array_almost_equal(vh.T @ vh, eye(3)) sigma = zeros((u.shape[0], vh.shape[0]), s.dtype.char) for i in range(len(s)): sigma[i, i] = s[i] assert_array_almost_equal(u @ sigma @ vh, a) def test_simple_singular(self): a = [[1, 2, 3], [1, 2, 3], [2, 5, 6]] for full_matrices in (True, False): u, s, vh = svd(a, full_matrices=full_matrices, lapack_driver=self.lapack_driver) assert_array_almost_equal(u.T @ u, eye(3)) assert_array_almost_equal(vh.T @ vh, eye(3)) sigma = zeros((u.shape[0], vh.shape[0]), s.dtype.char) for i in range(len(s)): sigma[i, i] = s[i] assert_array_almost_equal(u @ sigma @ vh, a) def test_simple_underdet(self): a = [[1, 2, 3], [4, 5, 6]] for full_matrices in (True, False): u, s, vh = svd(a, full_matrices=full_matrices, lapack_driver=self.lapack_driver) assert_array_almost_equal(u.T @ u, eye(u.shape[0])) sigma = zeros((u.shape[0], vh.shape[0]), s.dtype.char) for i in range(len(s)): sigma[i, i] = s[i] assert_array_almost_equal(u @ sigma @ vh, a) def test_simple_overdet(self): a = [[1, 2], [4, 5], [3, 4]] for full_matrices in (True, False): u, s, vh = svd(a, full_matrices=full_matrices, lapack_driver=self.lapack_driver) assert_array_almost_equal(u.T @ u, eye(u.shape[1])) assert_array_almost_equal(vh.T @ vh, eye(2)) sigma = zeros((u.shape[1], vh.shape[0]), s.dtype.char) for i in range(len(s)): sigma[i, i] = s[i] assert_array_almost_equal(u @ sigma @ vh, a) def test_random(self): rng = np.random.RandomState(1234) n = 20 m = 15 for i in range(3): for a in [rng.random([n, m]), rng.random([m, n])]: for full_matrices in (True, False): u, s, vh = svd(a, full_matrices=full_matrices, lapack_driver=self.lapack_driver) assert_array_almost_equal(u.T @ u, eye(u.shape[1])) assert_array_almost_equal(vh @ vh.T, eye(vh.shape[0])) sigma = zeros((u.shape[1], vh.shape[0]), s.dtype.char) for i in range(len(s)): sigma[i, i] = s[i] assert_array_almost_equal(u @ sigma @ vh, a) def test_simple_complex(self): a = [[1, 2, 3], [1, 2j, 3], [2, 5, 6]] for full_matrices in (True, False): u, s, vh = svd(a, full_matrices=full_matrices, lapack_driver=self.lapack_driver) assert_array_almost_equal(u.conj().T @ u, eye(u.shape[1])) assert_array_almost_equal(vh.conj().T @ vh, eye(vh.shape[0])) sigma = zeros((u.shape[0], vh.shape[0]), s.dtype.char) for i in range(len(s)): sigma[i, i] = s[i] assert_array_almost_equal(u @ sigma @ vh, a) def test_random_complex(self): rng = np.random.RandomState(1234) n = 20 m = 15 for i in range(3): for full_matrices in (True, False): for a in [rng.random([n, m]), rng.random([m, n])]: a = a + 1j*rng.random(list(a.shape)) u, s, vh = svd(a, full_matrices=full_matrices, lapack_driver=self.lapack_driver) assert_array_almost_equal(u.conj().T @ u, eye(u.shape[1])) # This fails when [m,n] # assert_array_almost_equal(vh.conj().T @ vh, # eye(len(vh),dtype=vh.dtype.char)) sigma = zeros((u.shape[1], vh.shape[0]), s.dtype.char) for i in range(len(s)): sigma[i, i] = s[i] assert_array_almost_equal(u @ sigma @ vh, a) def test_crash_1580(self): rng = np.random.RandomState(1234) sizes = [(13, 23), (30, 50), (60, 100)] for sz in sizes: for dt in [np.float32, np.float64, np.complex64, np.complex128]: a = rng.rand(*sz).astype(dt) # should not crash svd(a, lapack_driver=self.lapack_driver) def test_check_finite(self): a = [[1, 2, 3], [1, 20, 3], [2, 5, 6]] u, s, vh = svd(a, check_finite=False, lapack_driver=self.lapack_driver) assert_array_almost_equal(u.T @ u, eye(3)) assert_array_almost_equal(vh.T @ vh, eye(3)) sigma = zeros((u.shape[0], vh.shape[0]), s.dtype.char) for i in range(len(s)): sigma[i, i] = s[i] assert_array_almost_equal(u @ sigma @ vh, a) def test_gh_5039(self): # This is a smoke test for https://github.com/scipy/scipy/issues/5039 # # The following is reported to raise "ValueError: On entry to DGESDD # parameter number 12 had an illegal value". # `interp1d([1,2,3,4], [1,2,3,4], kind='cubic')` # This is reported to only show up on LAPACK 3.0.3. # # The matrix below is taken from the call to # `B = _fitpack._bsplmat(order, xk)` in interpolate._find_smoothest b = np.array( [[0.16666667, 0.66666667, 0.16666667, 0., 0., 0.], [0., 0.16666667, 0.66666667, 0.16666667, 0., 0.], [0., 0., 0.16666667, 0.66666667, 0.16666667, 0.], [0., 0., 0., 0.16666667, 0.66666667, 0.16666667]]) svd(b, lapack_driver=self.lapack_driver) @pytest.mark.skipif(not HAS_ILP64, reason="64-bit LAPACK required") @pytest.mark.slow def test_large_matrix(self): check_free_memory(free_mb=17000) A = np.zeros([1, 2**31], dtype=np.float32) A[0, -1] = 1 u, s, vh = svd(A, full_matrices=False) assert_allclose(s[0], 1.0) assert_allclose(u[0, 0] * vh[0, -1], 1.0) @pytest.mark.parametrize("m", [0, 1, 2]) @pytest.mark.parametrize("n", [0, 1, 2]) @pytest.mark.parametrize('dtype', DTYPES) def test_shape_dtype(self, m, n, dtype): a = np.zeros((m, n), dtype=dtype) k = min(m, n) dchar = a.dtype.char real_dchar = dchar.lower() if dchar in 'FD' else dchar u, s, v = svd(a) assert_equal(u.shape, (m, m)) assert_equal(u.dtype, dtype) assert_equal(s.shape, (k,)) assert_equal(s.dtype, np.dtype(real_dchar)) assert_equal(v.shape, (n, n)) assert_equal(v.dtype, dtype) u, s, v = svd(a, full_matrices=False) assert_equal(u.shape, (m, k)) assert_equal(u.dtype, dtype) assert_equal(s.shape, (k,)) assert_equal(s.dtype, np.dtype(real_dchar)) assert_equal(v.shape, (k, n)) assert_equal(v.dtype, dtype) s = svd(a, compute_uv=False) assert_equal(s.shape, (k,)) assert_equal(s.dtype, np.dtype(real_dchar)) @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64]) @pytest.mark.parametrize(("m", "n"), [(0, 0), (0, 2), (2, 0)]) def test_empty(self, dt, m, n): a0 = np.eye(3, dtype=dt) u0, s0, v0 = svd(a0) a = np.empty((m, n), dtype=dt) u, s, v = svd(a) assert_allclose(u, np.identity(m)) assert_allclose(s, np.empty((0,))) assert_allclose(v, np.identity(n)) assert u.dtype == u0.dtype assert v.dtype == v0.dtype assert s.dtype == s0.dtype u, s, v = svd(a, full_matrices=False) assert_allclose(u, np.empty((m, 0))) assert_allclose(s, np.empty((0,))) assert_allclose(v, np.empty((0, n))) assert u.dtype == u0.dtype assert v.dtype == v0.dtype assert s.dtype == s0.dtype s = svd(a, compute_uv=False) assert_allclose(s, np.empty((0,))) assert s.dtype == s0.dtype
TestSVD_GESDD
python
python__mypy
mypyc/test-data/fixtures/ir.py
{ "start": 14134, "end": 14178 }
class ____(ArithmeticError): pass
OverflowError
python
PyCQA__pylint
tests/functional/c/classes_meth_could_be_a_function.py
{ "start": 265, "end": 496 }
class ____: # disable "method could be a function" on classes which are not overriding # the factory method because in that case the usage of polymorphism is not # detected def makex(self): return XAsub()
Aimpl
python
getsentry__sentry
src/sentry/analytics/events/sso_enabled.py
{ "start": 68, "end": 206 }
class ____(analytics.Event): user_id: int organization_id: int provider: str analytics.register(SSOEnabledEvent)
SSOEnabledEvent
python
django__django
tests/inspectdb/models.py
{ "start": 270, "end": 468 }
class ____(models.Model): from_field = models.ForeignKey(People, models.CASCADE, db_column="from_id") author = models.ForeignKey(People, models.CASCADE, related_name="message_authors")
Message
python
huggingface__transformers
src/transformers/models/janus/modular_janus.py
{ "start": 22989, "end": 23167 }
class ____(Blip2VisionModel): def __init__(self, config: JanusVisionConfig): super().__init__(config) self.encoder = JanusVisionEncoder(config)
JanusVisionModel
python
PyCQA__pylint
pylint/config/_breaking_changes/__init__.py
{ "start": 1998, "end": 2133 }
class ____(NamedTuple): option: list[str] | str description: str | None = None new_value: str | None = None
OptionInformation
python
PyCQA__pylint
tests/functional/m/method_hidden.py
{ "start": 1011, "end": 1317 }
class ____: def __init__(self): self._bar = 42 self._baz = 84 @my_decorator def method(self): # E0202 return self._baz @method.setter def method(self, value): self._baz = value def do_something_with_baz(self, value): self.method = value
Foo
python
ijl__orjson
test/test_type.py
{ "start": 140, "end": 17790 }
class ____: def test_fragment(self): """ orjson.JSONDecodeError on fragments """ for val in ("n", "{", "[", "t"): pytest.raises(orjson.JSONDecodeError, orjson.loads, val) def test_invalid(self): """ orjson.JSONDecodeError on invalid """ for val in ('{"age", 44}', "[31337,]", "[,31337]", "[]]", "[,]"): pytest.raises(orjson.JSONDecodeError, orjson.loads, val) def test_str(self): """ str """ for obj, ref in (("blah", b'"blah"'), ("東京", b'"\xe6\x9d\xb1\xe4\xba\xac"')): assert orjson.dumps(obj) == ref assert orjson.loads(ref) == obj def test_str_latin1(self): """ str latin1 """ assert orjson.loads(orjson.dumps("üýþÿ")) == "üýþÿ" def test_str_long(self): """ str long """ for obj in ("aaaa" * 1024, "üýþÿ" * 1024, "好" * 1024, "�" * 1024): assert orjson.loads(orjson.dumps(obj)) == obj def test_str_2mib(self): ref = '🐈🐈🐈🐈🐈"üýa0s9999🐈🐈🐈🐈🐈9\0999\\9999' * 1024 * 50 assert orjson.loads(orjson.dumps(ref)) == ref def test_str_very_long(self): """ str long enough to trigger overflow in bytecount """ for obj in ("aaaa" * 20000, "üýþÿ" * 20000, "好" * 20000, "�" * 20000): assert orjson.loads(orjson.dumps(obj)) == obj def test_str_replacement(self): """ str roundtrip � """ assert orjson.dumps("�") == b'"\xef\xbf\xbd"' assert orjson.loads(b'"\xef\xbf\xbd"') == "�" def test_str_trailing_4_byte(self): ref = "うぞ〜😏🙌" assert orjson.loads(orjson.dumps(ref)) == ref def test_str_ascii_control(self): """ worst case format_escaped_str_with_escapes() allocation """ ref = "\x01\x1f" * 1024 * 16 assert orjson.loads(orjson.dumps(ref)) == ref assert orjson.loads(orjson.dumps(ref, option=orjson.OPT_INDENT_2)) == ref def test_str_escape_quote_0(self): assert orjson.dumps('"aaaaaaabb') == b'"\\"aaaaaaabb"' def test_str_escape_quote_1(self): assert orjson.dumps('a"aaaaaabb') == b'"a\\"aaaaaabb"' def test_str_escape_quote_2(self): assert orjson.dumps('aa"aaaaabb') == b'"aa\\"aaaaabb"' def test_str_escape_quote_3(self): assert orjson.dumps('aaa"aaaabb') == b'"aaa\\"aaaabb"' def test_str_escape_quote_4(self): assert orjson.dumps('aaaa"aaabb') == b'"aaaa\\"aaabb"' def test_str_escape_quote_5(self): assert orjson.dumps('aaaaa"aabb') == b'"aaaaa\\"aabb"' def test_str_escape_quote_6(self): assert orjson.dumps('aaaaaa"abb') == b'"aaaaaa\\"abb"' def test_str_escape_quote_7(self): assert orjson.dumps('aaaaaaa"bb') == b'"aaaaaaa\\"bb"' def test_str_escape_quote_8(self): assert orjson.dumps('aaaaaaaab"') == b'"aaaaaaaab\\""' def test_str_escape_quote_multi(self): assert ( orjson.dumps('aa"aaaaabbbbbbbbbbbbbbbbbbbb"bb') == b'"aa\\"aaaaabbbbbbbbbbbbbbbbbbbb\\"bb"' ) def test_str_escape_quote_buffer(self): orjson.dumps(['"' * 4096] * 1024) def test_str_escape_backslash_0(self): assert orjson.dumps("\\aaaaaaabb") == b'"\\\\aaaaaaabb"' def test_str_escape_backslash_1(self): assert orjson.dumps("a\\aaaaaabb") == b'"a\\\\aaaaaabb"' def test_str_escape_backslash_2(self): assert orjson.dumps("aa\\aaaaabb") == b'"aa\\\\aaaaabb"' def test_str_escape_backslash_3(self): assert orjson.dumps("aaa\\aaaabb") == b'"aaa\\\\aaaabb"' def test_str_escape_backslash_4(self): assert orjson.dumps("aaaa\\aaabb") == b'"aaaa\\\\aaabb"' def test_str_escape_backslash_5(self): assert orjson.dumps("aaaaa\\aabb") == b'"aaaaa\\\\aabb"' def test_str_escape_backslash_6(self): assert orjson.dumps("aaaaaa\\abb") == b'"aaaaaa\\\\abb"' def test_str_escape_backslash_7(self): assert orjson.dumps("aaaaaaa\\bb") == b'"aaaaaaa\\\\bb"' def test_str_escape_backslash_8(self): assert orjson.dumps("aaaaaaaab\\") == b'"aaaaaaaab\\\\"' def test_str_escape_backslash_multi(self): assert ( orjson.dumps("aa\\aaaaabbbbbbbbbbbbbbbbbbbb\\bb") == b'"aa\\\\aaaaabbbbbbbbbbbbbbbbbbbb\\\\bb"' ) def test_str_escape_backslash_buffer(self): orjson.dumps(["\\" * 4096] * 1024) def test_str_escape_x32_0(self): assert orjson.dumps("\taaaaaaabb") == b'"\\taaaaaaabb"' def test_str_escape_x32_1(self): assert orjson.dumps("a\taaaaaabb") == b'"a\\taaaaaabb"' def test_str_escape_x32_2(self): assert orjson.dumps("aa\taaaaabb") == b'"aa\\taaaaabb"' def test_str_escape_x32_3(self): assert orjson.dumps("aaa\taaaabb") == b'"aaa\\taaaabb"' def test_str_escape_x32_4(self): assert orjson.dumps("aaaa\taaabb") == b'"aaaa\\taaabb"' def test_str_escape_x32_5(self): assert orjson.dumps("aaaaa\taabb") == b'"aaaaa\\taabb"' def test_str_escape_x32_6(self): assert orjson.dumps("aaaaaa\tabb") == b'"aaaaaa\\tabb"' def test_str_escape_x32_7(self): assert orjson.dumps("aaaaaaa\tbb") == b'"aaaaaaa\\tbb"' def test_str_escape_x32_8(self): assert orjson.dumps("aaaaaaaab\t") == b'"aaaaaaaab\\t"' def test_str_escape_x32_multi(self): assert ( orjson.dumps("aa\taaaaabbbbbbbbbbbbbbbbbbbb\tbb") == b'"aa\\taaaaabbbbbbbbbbbbbbbbbbbb\\tbb"' ) def test_str_escape_x32_buffer(self): orjson.dumps(["\t" * 4096] * 1024) def test_str_emoji(self): ref = "®️" assert orjson.loads(orjson.dumps(ref)) == ref def test_str_emoji_escape(self): ref = '/"®️/"' assert orjson.loads(orjson.dumps(ref)) == ref def test_very_long_list(self): orjson.dumps([[]] * 1024 * 16) def test_very_long_list_pretty(self): orjson.dumps([[]] * 1024 * 16, option=orjson.OPT_INDENT_2) def test_very_long_dict(self): orjson.dumps([{}] * 1024 * 16) def test_very_long_dict_pretty(self): orjson.dumps([{}] * 1024 * 16, option=orjson.OPT_INDENT_2) def test_very_long_str_empty(self): orjson.dumps([""] * 1024 * 16) def test_very_long_str_empty_pretty(self): orjson.dumps([""] * 1024 * 16, option=orjson.OPT_INDENT_2) def test_very_long_str_not_empty(self): orjson.dumps(["a"] * 1024 * 16) def test_very_long_str_not_empty_pretty(self): orjson.dumps(["a"] * 1024 * 16, option=orjson.OPT_INDENT_2) def test_very_long_bool(self): orjson.dumps([True] * 1024 * 16) def test_very_long_bool_pretty(self): orjson.dumps([True] * 1024 * 16, option=orjson.OPT_INDENT_2) def test_very_long_int(self): orjson.dumps([(2**64) - 1] * 1024 * 16) def test_very_long_int_pretty(self): orjson.dumps([(2**64) - 1] * 1024 * 16, option=orjson.OPT_INDENT_2) def test_very_long_float(self): orjson.dumps([sys.float_info.max] * 1024 * 16) def test_very_long_float_pretty(self): orjson.dumps([sys.float_info.max] * 1024 * 16, option=orjson.OPT_INDENT_2) def test_str_surrogates_loads(self): """ str unicode surrogates loads() """ pytest.raises(orjson.JSONDecodeError, orjson.loads, '"\ud800"') pytest.raises(orjson.JSONDecodeError, orjson.loads, '"\ud83d\ude80"') pytest.raises(orjson.JSONDecodeError, orjson.loads, '"\udcff"') pytest.raises( orjson.JSONDecodeError, orjson.loads, b'"\xed\xa0\xbd\xed\xba\x80"', ) # \ud83d\ude80 def test_str_surrogates_dumps(self): """ str unicode surrogates dumps() """ pytest.raises(orjson.JSONEncodeError, orjson.dumps, "\ud800") pytest.raises(orjson.JSONEncodeError, orjson.dumps, "\ud83d\ude80") pytest.raises(orjson.JSONEncodeError, orjson.dumps, "\udcff") pytest.raises(orjson.JSONEncodeError, orjson.dumps, {"\ud83d\ude80": None}) pytest.raises( orjson.JSONEncodeError, orjson.dumps, b"\xed\xa0\xbd\xed\xba\x80", ) # \ud83d\ude80 def test_bytes_dumps(self): """ bytes dumps not supported """ with pytest.raises(orjson.JSONEncodeError): orjson.dumps([b"a"]) def test_bytes_loads(self): """ bytes loads """ assert orjson.loads(b"[]") == [] def test_bytearray_loads(self): """ bytearray loads """ arr = bytearray() arr.extend(b"[]") assert orjson.loads(arr) == [] @pytest.mark.skipif(SUPPORTS_MEMORYVIEW, reason="memoryview not supported") def test_memoryview_loads_supported(self): """ memoryview loads supported """ arr = bytearray() arr.extend(b"[]") assert orjson.loads(memoryview(arr)) == [] @pytest.mark.skipif(not SUPPORTS_MEMORYVIEW, reason="memoryview supported") def test_memoryview_loads_unsupported(self): """ memoryview loads unsupported """ arr = bytearray() arr.extend(b"[]") with pytest.raises(orjson.JSONEncodeError): orjson.loads(memoryview(arr)) def test_bytesio_loads(self): """ BytesIO loads """ arr = io.BytesIO(b"[]") assert orjson.loads(arr.getbuffer()) == [] def test_bool(self): """ bool """ for obj, ref in ((True, "true"), (False, "false")): assert orjson.dumps(obj) == ref.encode("utf-8") assert orjson.loads(ref) == obj def test_bool_true_array(self): """ bool true array """ obj = [True] * 256 ref = ("[" + ("true," * 255) + "true]").encode("utf-8") assert orjson.dumps(obj) == ref assert orjson.loads(ref) == obj def test_bool_false_array(self): """ bool false array """ obj = [False] * 256 ref = ("[" + ("false," * 255) + "false]").encode("utf-8") assert orjson.dumps(obj) == ref assert orjson.loads(ref) == obj def test_none(self): """ null """ obj = None ref = "null" assert orjson.dumps(obj) == ref.encode("utf-8") assert orjson.loads(ref) == obj def test_int(self): """ int compact and non-compact """ obj = [-5000, -1000, -10, -5, -2, -1, 0, 1, 2, 5, 10, 1000, 50000] ref = b"[-5000,-1000,-10,-5,-2,-1,0,1,2,5,10,1000,50000]" assert orjson.dumps(obj) == ref assert orjson.loads(ref) == obj def test_null_array(self): """ null array """ obj = [None] * 256 ref = ("[" + ("null," * 255) + "null]").encode("utf-8") assert orjson.dumps(obj) == ref assert orjson.loads(ref) == obj def test_nan_dumps(self): """ NaN serializes to null """ assert orjson.dumps(float("NaN")) == b"null" def test_nan_loads(self): """ NaN is not valid JSON """ with pytest.raises(orjson.JSONDecodeError): orjson.loads("[NaN]") with pytest.raises(orjson.JSONDecodeError): orjson.loads("[nan]") def test_infinity_dumps(self): """ Infinity serializes to null """ assert orjson.dumps(float("Infinity")) == b"null" def test_infinity_loads(self): """ Infinity, -Infinity is not valid JSON """ with pytest.raises(orjson.JSONDecodeError): orjson.loads("[infinity]") with pytest.raises(orjson.JSONDecodeError): orjson.loads("[Infinity]") with pytest.raises(orjson.JSONDecodeError): orjson.loads("[-Infinity]") with pytest.raises(orjson.JSONDecodeError): orjson.loads("[-infinity]") def test_int_53(self): """ int 53-bit """ for val in (9007199254740991, -9007199254740991): assert orjson.loads(str(val)) == val assert orjson.dumps(val, option=orjson.OPT_STRICT_INTEGER) == str( val, ).encode("utf-8") def test_int_53_exc(self): """ int 53-bit exception on 64-bit """ for val in (9007199254740992, -9007199254740992): with pytest.raises(orjson.JSONEncodeError): orjson.dumps(val, option=orjson.OPT_STRICT_INTEGER) def test_int_53_exc_usize(self): """ int 53-bit exception on 64-bit usize """ for val in (9223372036854775808, 18446744073709551615): with pytest.raises(orjson.JSONEncodeError): orjson.dumps(val, option=orjson.OPT_STRICT_INTEGER) def test_int_53_exc_128(self): """ int 53-bit exception on 128-bit """ val = 2**65 with pytest.raises(orjson.JSONEncodeError): orjson.dumps(val, option=orjson.OPT_STRICT_INTEGER) def test_int_64(self): """ int 64-bit """ for val in (9223372036854775807, -9223372036854775807): assert orjson.loads(str(val)) == val assert orjson.dumps(val) == str(val).encode("utf-8") def test_uint_64(self): """ uint 64-bit """ for val in (0, 9223372036854775808, 18446744073709551615): assert orjson.loads(str(val)) == val assert orjson.dumps(val) == str(val).encode("utf-8") def test_int_128(self): """ int 128-bit """ for val in (18446744073709551616, -9223372036854775809): pytest.raises(orjson.JSONEncodeError, orjson.dumps, val) def test_float(self): """ float """ assert -1.1234567893 == orjson.loads("-1.1234567893") assert -1.234567893 == orjson.loads("-1.234567893") assert -1.34567893 == orjson.loads("-1.34567893") assert -1.4567893 == orjson.loads("-1.4567893") assert -1.567893 == orjson.loads("-1.567893") assert -1.67893 == orjson.loads("-1.67893") assert -1.7893 == orjson.loads("-1.7893") assert -1.893 == orjson.loads("-1.893") assert -1.3 == orjson.loads("-1.3") assert 1.1234567893 == orjson.loads("1.1234567893") assert 1.234567893 == orjson.loads("1.234567893") assert 1.34567893 == orjson.loads("1.34567893") assert 1.4567893 == orjson.loads("1.4567893") assert 1.567893 == orjson.loads("1.567893") assert 1.67893 == orjson.loads("1.67893") assert 1.7893 == orjson.loads("1.7893") assert 1.893 == orjson.loads("1.893") assert 1.3 == orjson.loads("1.3") def test_float_precision_loads(self): """ float precision loads() """ assert orjson.loads("31.245270191439438") == 31.245270191439438 assert orjson.loads("-31.245270191439438") == -31.245270191439438 assert orjson.loads("121.48791951161945") == 121.48791951161945 assert orjson.loads("-121.48791951161945") == -121.48791951161945 assert orjson.loads("100.78399658203125") == 100.78399658203125 assert orjson.loads("-100.78399658203125") == -100.78399658203125 def test_float_precision_dumps(self): """ float precision dumps() """ assert orjson.dumps(31.245270191439438) == b"31.245270191439438" assert orjson.dumps(-31.245270191439438) == b"-31.245270191439438" assert orjson.dumps(121.48791951161945) == b"121.48791951161945" assert orjson.dumps(-121.48791951161945) == b"-121.48791951161945" assert orjson.dumps(100.78399658203125) == b"100.78399658203125" assert orjson.dumps(-100.78399658203125) == b"-100.78399658203125" def test_float_edge(self): """ float edge cases """ assert orjson.dumps(0.8701) == b"0.8701" assert orjson.loads("0.8701") == 0.8701 assert ( orjson.loads("0.0000000000000000000000000000000000000000000000000123e50") == 1.23 ) assert orjson.loads("0.4e5") == 40000.0 assert orjson.loads("0.00e-00") == 0.0 assert orjson.loads("0.4e-001") == 0.04 assert orjson.loads("0.123456789e-12") == 1.23456789e-13 assert orjson.loads("1.234567890E+34") == 1.23456789e34 assert orjson.loads("23456789012E66") == 2.3456789012e76 def test_float_notation(self): """ float notation """ for val in ("1.337E40", "1.337e+40", "1337e40", "1.337E-4"): obj = orjson.loads(val) assert obj == float(val) assert orjson.dumps(val) == (f'"{val}"').encode("utf-8") def test_list(self): """ list """ obj = ["a", "😊", True, {"b": 1.1}, 2] ref = '["a","😊",true,{"b":1.1},2]' assert orjson.dumps(obj) == ref.encode("utf-8") assert orjson.loads(ref) == obj def test_tuple(self): """ tuple """ obj = ("a", "😊", True, {"b": 1.1}, 2) ref = '["a","😊",true,{"b":1.1},2]' assert orjson.dumps(obj) == ref.encode("utf-8") assert orjson.loads(ref) == list(obj) def test_object(self): """ object() dumps() """ with pytest.raises(orjson.JSONEncodeError): orjson.dumps(object())
TestType
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/dialects/mysql/dml.py
{ "start": 3183, "end": 7560 }
class ____(StandardInsert): """MySQL-specific implementation of INSERT. Adds methods for MySQL-specific syntaxes such as ON DUPLICATE KEY UPDATE. The :class:`~.mysql.Insert` object is created using the :func:`sqlalchemy.dialects.mysql.insert` function. """ stringify_dialect = "mysql" inherit_cache = True @property def inserted( self, ) -> ReadOnlyColumnCollection[str, KeyedColumnElement[Any]]: """Provide the "inserted" namespace for an ON DUPLICATE KEY UPDATE statement MySQL's ON DUPLICATE KEY UPDATE clause allows reference to the row that would be inserted, via a special function called ``VALUES()``. This attribute provides all columns in this row to be referenceable such that they will render within a ``VALUES()`` function inside the ON DUPLICATE KEY UPDATE clause. The attribute is named ``.inserted`` so as not to conflict with the existing :meth:`_expression.Insert.values` method. .. tip:: The :attr:`_mysql.Insert.inserted` attribute is an instance of :class:`_expression.ColumnCollection`, which provides an interface the same as that of the :attr:`_schema.Table.c` collection described at :ref:`metadata_tables_and_columns`. With this collection, ordinary names are accessible like attributes (e.g. ``stmt.inserted.some_column``), but special names and dictionary method names should be accessed using indexed access, such as ``stmt.inserted["column name"]`` or ``stmt.inserted["values"]``. See the docstring for :class:`_expression.ColumnCollection` for further examples. .. seealso:: :ref:`mysql_insert_on_duplicate_key_update` - example of how to use :attr:`_expression.Insert.inserted` """ return self.inserted_alias.columns @util.memoized_property def inserted_alias(self) -> NamedFromClause: return alias(self.table, name="inserted") @_exclusive_against( "_post_values_clause", msgs={ "_post_values_clause": "This Insert construct already " "has an ON DUPLICATE KEY clause present" }, ) def on_duplicate_key_update(self, *args: _UpdateArg, **kw: Any) -> Self: r""" Specifies the ON DUPLICATE KEY UPDATE clause. :param \**kw: Column keys linked to UPDATE values. The values may be any SQL expression or supported literal Python values. .. warning:: This dictionary does **not** take into account Python-specified default UPDATE values or generation functions, e.g. those specified using :paramref:`_schema.Column.onupdate`. These values will not be exercised for an ON DUPLICATE KEY UPDATE style of UPDATE, unless values are manually specified here. :param \*args: As an alternative to passing key/value parameters, a dictionary or list of 2-tuples can be passed as a single positional argument. Passing a single dictionary is equivalent to the keyword argument form:: insert().on_duplicate_key_update({"name": "some name"}) Passing a list of 2-tuples indicates that the parameter assignments in the UPDATE clause should be ordered as sent, in a manner similar to that described for the :class:`_expression.Update` construct overall in :ref:`tutorial_parameter_ordered_updates`:: insert().on_duplicate_key_update( [ ("name", "some name"), ("value", "some value"), ] ) .. seealso:: :ref:`mysql_insert_on_duplicate_key_update` """ if args and kw: raise exc.ArgumentError( "Can't pass kwargs and positional arguments simultaneously" ) if args: if len(args) > 1: raise exc.ArgumentError( "Only a single dictionary or list of tuples " "is accepted positionally." ) values = args[0] else: values = kw return self.ext(OnDuplicateClause(self.inserted_alias, values))
Insert
python
spack__spack
var/spack/test_repos/spack_repo/builtin_mock/packages/virtual_abi_2/package.py
{ "start": 217, "end": 614 }
class ____(Package): """ This package provides `virtual-with-abi` and is conditionally ABI compatible with `virtual-abi-multi` """ homepage = "https://www.example.com" has_code = False version("1.0") provides("virtual-with-abi") can_splice("virtual-abi-multi@1.0 abi=two", when="@1.0") def install(self, spec, prefix): touch(prefix.foo)
VirtualAbi2
python
airbytehq__airbyte
airbyte-integrations/connectors/destination-qdrant/destination_qdrant/config.py
{ "start": 1879, "end": 1959 }
class ____(VectorDBConfigModel): indexing: QdrantIndexingConfigModel
ConfigModel
python
numba__numba
numba/tests/test_linalg.py
{ "start": 88450, "end": 91243 }
class ____(TestLinalgBase): """ Tests for np.trace. """ def setUp(self): super(TestTrace, self).setUp() # compile two versions, one with and one without the offset kwarg self.cfunc_w_offset = jit(nopython=True)(trace_matrix) self.cfunc_no_offset = jit(nopython=True)(trace_matrix_no_offset) def assert_int_offset(self, cfunc, a, **kwargs): # validate first arg is ok cfunc(a) # pass in kwarg and assert fail with self.assertRaises(errors.TypingError): cfunc(a, **kwargs) def test_trace(self): def check(a, **kwargs): if 'offset' in kwargs: expected = trace_matrix(a, **kwargs) cfunc = self.cfunc_w_offset else: expected = trace_matrix_no_offset(a, **kwargs) cfunc = self.cfunc_no_offset got = cfunc(a, **kwargs) res = 5 * np.finfo(a.dtype).resolution np.testing.assert_allclose(got, expected, rtol=res, atol=res) # Ensure proper resource management with self.assertNoNRTLeak(): cfunc(a, **kwargs) # test: column vector, tall, wide, square, row vector # prime sizes sizes = [(7, 1), (11, 5), (5, 11), (3, 3), (1, 7)] # offsets to cover the range of the matrix sizes above offsets = [-13, -12, -11] + list(range(-10, 10)) + [11, 12, 13] for size, offset, dtype, order in \ product(sizes, offsets, self.dtypes, 'FC'): a = self.specific_sample_matrix(size, dtype, order) check(a, offset=offset) if offset == 0: check(a) a = np.empty((0, 0), dtype=dtype, order=order) check(a, offset=offset) if offset == 0: check(a) rn = "trace" # Dimension issue self.assert_wrong_dimensions(rn, self.cfunc_w_offset, (np.ones(10, dtype=np.float64), 1), False) self.assert_wrong_dimensions(rn, self.cfunc_no_offset, (np.ones(10, dtype=np.float64),), False) # non-integer supplied as exponent self.assert_int_offset( self.cfunc_w_offset, np.ones( (2, 2)), offset=1.2) def test_trace_w_optional_input(self): "Issue 2314" @jit("(optional(float64[:,:]),)", nopython=True) def tested(a): return np.trace(a) a = np.ones((5, 5), dtype=np.float64) tested(a) with self.assertRaises(TypeError) as raises: tested(None) errmsg = str(raises.exception) self.assertEqual('expected array(float64, 2d, A), got None', errmsg)
TestTrace
python
weaviate__weaviate-python-client
weaviate/collections/classes/config.py
{ "start": 8856, "end": 8930 }
class ____(_ConfigCreateModel): b: float k1: float
_BM25ConfigCreate