





"""simple docstring"""




import shutil
import tempfile
import unittest
from unittest.mock import patch

from transformers import (
    DefaultFlowCallback,
    IntervalStrategy,
    PrinterCallback,
    ProgressCallback,
    Trainer,
    TrainerCallback,
    TrainingArguments,
    is_torch_available,
)
from transformers.testing_utils import require_torch


if is_torch_available():
		from transformers.trainer import DEFAULT_CALLBACKS

		from .test_trainer import RegressionDataset, RegressionModelConfig, RegressionPreTrainedModel


class 			__UpperCamelCase							(		a__		):






							def __init__(  self )      ->					Any:
								a :						List[Any]      =							[]






							def        __a  (  self ,   lowerCAmelCase__ ,   lowerCAmelCase__ ,   lowerCAmelCase__ ,   **lowerCAmelCase__ )      ->					List[Any]:
								self.events.append("on_init_end" )






							def        __a  (  self ,   lowerCAmelCase__ ,   lowerCAmelCase__ ,   lowerCAmelCase__ ,   **lowerCAmelCase__ )      ->					List[Any]:
								self.events.append("on_train_begin" )






							def        __a  (  self ,   lowerCAmelCase__ ,   lowerCAmelCase__ ,   lowerCAmelCase__ ,   **lowerCAmelCase__ )      ->					List[Any]:
								self.events.append("on_train_end" )






							def        __a  (  self ,   lowerCAmelCase__ ,   lowerCAmelCase__ ,   lowerCAmelCase__ ,   **lowerCAmelCase__ )      ->					Tuple:
								self.events.append("on_epoch_begin" )






							def        __a  (  self ,   lowerCAmelCase__ ,   lowerCAmelCase__ ,   lowerCAmelCase__ ,   **lowerCAmelCase__ )      ->					Optional[int]:
								self.events.append("on_epoch_end" )






							def        __a  (  self ,   lowerCAmelCase__ ,   lowerCAmelCase__ ,   lowerCAmelCase__ ,   **lowerCAmelCase__ )      ->					List[str]:
								self.events.append("on_step_begin" )






							def        __a  (  self ,   lowerCAmelCase__ ,   lowerCAmelCase__ ,   lowerCAmelCase__ ,   **lowerCAmelCase__ )      ->					Tuple:
								self.events.append("on_step_end" )






							def        __a  (  self ,   lowerCAmelCase__ ,   lowerCAmelCase__ ,   lowerCAmelCase__ ,   **lowerCAmelCase__ )      ->					Dict:
								self.events.append("on_evaluate" )






							def        __a  (  self ,   lowerCAmelCase__ ,   lowerCAmelCase__ ,   lowerCAmelCase__ ,   **lowerCAmelCase__ )      ->					Dict:
								self.events.append("on_predict" )






							def        __a  (  self ,   lowerCAmelCase__ ,   lowerCAmelCase__ ,   lowerCAmelCase__ ,   **lowerCAmelCase__ )      ->					Tuple:
								self.events.append("on_save" )






							def        __a  (  self ,   lowerCAmelCase__ ,   lowerCAmelCase__ ,   lowerCAmelCase__ ,   **lowerCAmelCase__ )      ->					Tuple:
								self.events.append("on_log" )






							def        __a  (  self ,   lowerCAmelCase__ ,   lowerCAmelCase__ ,   lowerCAmelCase__ ,   **lowerCAmelCase__ )      ->					List[str]:
								self.events.append("on_prediction_step" )


@require_torch
class 			__UpperCamelCase							(		unittest.TestCase		):






							def        __a  (  self )      ->					str:
								a :						Union[str, Any]      =							tempfile.mkdtemp()






							def        __a  (  self )      ->					Union[str, Any]:
								shutil.rmtree(self.output_dir )






							def        __a  (  self ,   lowerCAmelCase__=0 ,   lowerCAmelCase__=0 ,   lowerCAmelCase__=64 ,   lowerCAmelCase__=64 ,   lowerCAmelCase__=None ,   lowerCAmelCase__=False ,   **lowerCAmelCase__ )      ->					List[str]:
								# disable_tqdm in TrainingArguments has a flaky default since it depends on the level of logging. We make sure
								# its set to False since the tests later on depend on its value.
								a :						Optional[int]      =							RegressionDataset(length=lowerCAmelCase__ )
								a :						List[str]      =							RegressionDataset(length=lowerCAmelCase__ )
								a :						int      =							RegressionModelConfig(a=lowerCAmelCase__ ,   b=lowerCAmelCase__ )
								a :						str      =							RegressionPreTrainedModel(lowerCAmelCase__ )

								a :						str      =							TrainingArguments(self.output_dir ,   disable_tqdm=lowerCAmelCase__ ,   report_to=[] ,   **lowerCAmelCase__ )
								return Trainer(
								    lowerCAmelCase__ ,   lowerCAmelCase__ ,   train_dataset=lowerCAmelCase__ ,   eval_dataset=lowerCAmelCase__ ,   callbacks=lowerCAmelCase__ ,   )






							def        __a  (  self ,   lowerCAmelCase__ ,   lowerCAmelCase__ )      ->					Optional[int]:
								self.assertEqual(len(lowerCAmelCase__ ) ,   len(lowerCAmelCase__ ) )

								# Order doesn't matter
								a :						Union[str, Any]      =							sorted(lowerCAmelCase__ ,   key=lambda lowerCAmelCase__ : cb.__name__ if isinstance(lowerCAmelCase__ ,   lowerCAmelCase__ ) else cb.__class__.__name__ )
								a :						Any      =							sorted(lowerCAmelCase__ ,   key=lambda lowerCAmelCase__ : cb.__name__ if isinstance(lowerCAmelCase__ ,   lowerCAmelCase__ ) else cb.__class__.__name__ )

								for cba, cba in zip(lowerCAmelCase__ ,   lowerCAmelCase__ ):
									if isinstance(lowerCAmelCase__ ,   lowerCAmelCase__ ) and isinstance(lowerCAmelCase__ ,   lowerCAmelCase__ ):
										self.assertEqual(lowerCAmelCase__ ,   lowerCAmelCase__ )
									elif isinstance(lowerCAmelCase__ ,   lowerCAmelCase__ ) and not isinstance(lowerCAmelCase__ ,   lowerCAmelCase__ ):
										self.assertEqual(lowerCAmelCase__ ,   cba.__class__ )
									elif not isinstance(lowerCAmelCase__ ,   lowerCAmelCase__ ) and isinstance(lowerCAmelCase__ ,   lowerCAmelCase__ ):
										self.assertEqual(cba.__class__ ,   lowerCAmelCase__ )
									else:
										self.assertEqual(lowerCAmelCase__ ,   lowerCAmelCase__ )






							def        __a  (  self ,   lowerCAmelCase__ )      ->					Tuple:
								a :						List[str]      =							["on_init_end", "on_train_begin"]
								a :						str      =							0
								a :						List[str]      =							len(trainer.get_eval_dataloader() )
								a :						List[str]      =							["on_prediction_step"] * len(trainer.get_eval_dataloader() ) + ["on_log", "on_evaluate"]
								for _ in range(trainer.state.num_train_epochs ):
									expected_events.append("on_epoch_begin" )
									for _ in range(lowerCAmelCase__ ):
										step += 1
										expected_events += ["on_step_begin", "on_step_end"]
										if step % trainer.args.logging_steps == 0:
											expected_events.append("on_log" )
										if trainer.args.evaluation_strategy == IntervalStrategy.STEPS and step % trainer.args.eval_steps == 0:
											expected_events += evaluation_events.copy()
										if step % trainer.args.save_steps == 0:
											expected_events.append("on_save" )
									expected_events.append("on_epoch_end" )
									if trainer.args.evaluation_strategy == IntervalStrategy.EPOCH:
										expected_events += evaluation_events.copy()
								expected_events += ["on_log", "on_train_end"]
								return expected_events






							def        __a  (  self )      ->					Any:
								a :						Union[str, Any]      =							self.get_trainer()
								a :						Dict      =							DEFAULT_CALLBACKS.copy() + [ProgressCallback]
								self.check_callbacks_equality(trainer.callback_handler.callbacks ,   lowerCAmelCase__ )

								# Callbacks passed at init are added to the default callbacks
								a :						Optional[int]      =							self.get_trainer(callbacks=[MyTestTrainerCallback] )
								expected_callbacks.append(lowerCAmelCase__ )
								self.check_callbacks_equality(trainer.callback_handler.callbacks ,   lowerCAmelCase__ )

								# TrainingArguments.disable_tqdm controls if use ProgressCallback or PrinterCallback
								a :						List[str]      =							self.get_trainer(disable_tqdm=lowerCAmelCase__ )
								a :						Optional[int]      =							DEFAULT_CALLBACKS.copy() + [PrinterCallback]
								self.check_callbacks_equality(trainer.callback_handler.callbacks ,   lowerCAmelCase__ )






							def        __a  (  self )      ->					Any:
								a :						List[Any]      =							DEFAULT_CALLBACKS.copy() + [ProgressCallback]
								a :						Tuple      =							self.get_trainer()

								# We can add, pop, or remove by class name
								trainer.remove_callback(lowerCAmelCase__ )
								expected_callbacks.remove(lowerCAmelCase__ )
								self.check_callbacks_equality(trainer.callback_handler.callbacks ,   lowerCAmelCase__ )

								a :						List[str]      =							self.get_trainer()
								a :						int      =							trainer.pop_callback(lowerCAmelCase__ )
								self.assertEqual(cb.__class__ ,   lowerCAmelCase__ )
								self.check_callbacks_equality(trainer.callback_handler.callbacks ,   lowerCAmelCase__ )

								trainer.add_callback(lowerCAmelCase__ )
								expected_callbacks.insert(0 ,   lowerCAmelCase__ )
								self.check_callbacks_equality(trainer.callback_handler.callbacks ,   lowerCAmelCase__ )

								# We can also add, pop, or remove by instance
								a :						List[str]      =							self.get_trainer()
								a :						List[str]      =							trainer.callback_handler.callbacks[0]
								trainer.remove_callback(lowerCAmelCase__ )
								expected_callbacks.remove(lowerCAmelCase__ )
								self.check_callbacks_equality(trainer.callback_handler.callbacks ,   lowerCAmelCase__ )

								a :						List[str]      =							self.get_trainer()
								a :						Optional[Any]      =							trainer.callback_handler.callbacks[0]
								a :						Union[str, Any]      =							trainer.pop_callback(lowerCAmelCase__ )
								self.assertEqual(lowerCAmelCase__ ,   lowerCAmelCase__ )
								self.check_callbacks_equality(trainer.callback_handler.callbacks ,   lowerCAmelCase__ )

								trainer.add_callback(lowerCAmelCase__ )
								expected_callbacks.insert(0 ,   lowerCAmelCase__ )
								self.check_callbacks_equality(trainer.callback_handler.callbacks ,   lowerCAmelCase__ )






							def        __a  (  self )      ->					Optional[int]:
								import warnings

								# XXX: for now ignore scatter_gather warnings in this test since it's not relevant to what's being tested
								warnings.simplefilter(action="ignore" ,   category=lowerCAmelCase__ )

								a :						Optional[int]      =							self.get_trainer(callbacks=[MyTestTrainerCallback] )
								trainer.train()
								a :						Optional[Any]      =							trainer.callback_handler.callbacks[-2].events
								self.assertEqual(lowerCAmelCase__ ,   self.get_expected_events(lowerCAmelCase__ ) )

								# Independent log/save/eval
								a :						Tuple      =							self.get_trainer(callbacks=[MyTestTrainerCallback] ,   logging_steps=5 )
								trainer.train()
								a :						Optional[int]      =							trainer.callback_handler.callbacks[-2].events
								self.assertEqual(lowerCAmelCase__ ,   self.get_expected_events(lowerCAmelCase__ ) )

								a :						Tuple      =							self.get_trainer(callbacks=[MyTestTrainerCallback] ,   save_steps=5 )
								trainer.train()
								a :						Tuple      =							trainer.callback_handler.callbacks[-2].events
								self.assertEqual(lowerCAmelCase__ ,   self.get_expected_events(lowerCAmelCase__ ) )

								a :						List[str]      =							self.get_trainer(callbacks=[MyTestTrainerCallback] ,   eval_steps=5 ,   evaluation_strategy="steps" )
								trainer.train()
								a :						Tuple      =							trainer.callback_handler.callbacks[-2].events
								self.assertEqual(lowerCAmelCase__ ,   self.get_expected_events(lowerCAmelCase__ ) )

								a :						Optional[Any]      =							self.get_trainer(callbacks=[MyTestTrainerCallback] ,   evaluation_strategy="epoch" )
								trainer.train()
								a :						List[str]      =							trainer.callback_handler.callbacks[-2].events
								self.assertEqual(lowerCAmelCase__ ,   self.get_expected_events(lowerCAmelCase__ ) )

								# A bit of everything
								a :						List[str]      =							self.get_trainer(
								    callbacks=[MyTestTrainerCallback] ,   logging_steps=3 ,   save_steps=10 ,   eval_steps=5 ,   evaluation_strategy="steps" ,   )
								trainer.train()
								a :						int      =							trainer.callback_handler.callbacks[-2].events
								self.assertEqual(lowerCAmelCase__ ,   self.get_expected_events(lowerCAmelCase__ ) )

								# warning should be emitted for duplicated callbacks
								with patch("transformers.trainer_callback.logger.warning" ) as warn_mock:
									a :						int      =							self.get_trainer(
									    callbacks=[MyTestTrainerCallback, MyTestTrainerCallback] ,   )
									assert str(lowerCAmelCase__ ) in warn_mock.call_args[0][0]









"""simple docstring"""




class 			__UpperCamelCase							:  # Public class to implement a graph






							def __init__(  self ,   lowerCAmelCase__ ,   lowerCAmelCase__ ,   lowerCAmelCase__ )      ->					None:
								a :						int      =							row
								a :						Tuple      =							col
								a :						Optional[int]      =							graph






							def        __a  (  self ,   lowerCAmelCase__ ,   lowerCAmelCase__ ,   lowerCAmelCase__ )      ->					bool:
								return (
								    0 <= i < self.ROW
								    and 0 <= j < self.COL
								    and not visited[i][j]
								    and self.graph[i][j]
								)






							def        __a  (  self ,   lowerCAmelCase__ ,   lowerCAmelCase__ ,   lowerCAmelCase__ )      ->					None:
								# Checking all 8 elements surrounding nth element
								a :						Optional[Any]      =							[-1, -1, -1, 0, 0, 1, 1, 1]  # Coordinate order
								a :						str      =							[-1, 0, 1, -1, 1, -1, 0, 1]
								a :						str      =							True  # Make those cells visited
								for k in range(8 ):
									if self.is_safe(i + row_nbr[k] ,   j + col_nbr[k] ,   lowerCAmelCase__ ):
										self.diffs(i + row_nbr[k] ,   j + col_nbr[k] ,   lowerCAmelCase__ )






							def        __a  (  self )      ->					int:  # And finally, count all islands.
								a :						Union[str, Any]      =							[[False for j in range(self.COL )] for i in range(self.ROW )]
								a :						Dict      =							0
								for i in range(self.ROW ):
									for j in range(self.COL ):
										if visited[i][j] is False and self.graph[i][j] == 1:
											self.diffs(lowerCAmelCase__ ,   lowerCAmelCase__ ,   lowerCAmelCase__ )
											count += 1
								return count


