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 						SCREAMING_SNAKE_CASE				( __a					):





							"""simple docstring"""

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

							def       __A (  self:   Any		,     __A:   Dict		,     __A:   Dict		,     __A:   List[Any]		,     **__A:   Dict   )    ->				int:
												self.events.append('''on_init_end'''   )

							def       __A (  self:   Optional[int]		,     __A:   Dict		,     __A:   Optional[Any]		,     __A:   Tuple		,     **__A:   Any   )    ->				List[str]:
												self.events.append('''on_train_begin'''   )

							def       __A (  self:   Dict		,     __A:   Optional[Any]		,     __A:   Tuple		,     __A:   str		,     **__A:   List[str]   )    ->				Dict:
												self.events.append('''on_train_end'''   )

							def       __A (  self:   List[str]		,     __A:   str		,     __A:   int		,     __A:   Optional[int]		,     **__A:   Optional[Any]   )    ->				Tuple:
												self.events.append('''on_epoch_begin'''   )

							def       __A (  self:   Optional[Any]		,     __A:   Optional[int]		,     __A:   List[str]		,     __A:   Optional[Any]		,     **__A:   Optional[Any]   )    ->				List[Any]:
												self.events.append('''on_epoch_end'''   )

							def       __A (  self:   List[Any]		,     __A:   Optional[Any]		,     __A:   Any		,     __A:   Tuple		,     **__A:   Optional[Any]   )    ->				Optional[int]:
												self.events.append('''on_step_begin'''   )

							def       __A (  self:   List[Any]		,     __A:   Dict		,     __A:   str		,     __A:   Optional[Any]		,     **__A:   Tuple   )    ->				Any:
												self.events.append('''on_step_end'''   )

							def       __A (  self:   Dict		,     __A:   Tuple		,     __A:   Tuple		,     __A:   List[Any]		,     **__A:   Optional[Any]   )    ->				List[Any]:
												self.events.append('''on_evaluate'''   )

							def       __A (  self:   Tuple		,     __A:   Optional[Any]		,     __A:   Any		,     __A:   Optional[int]		,     **__A:   int   )    ->				Tuple:
												self.events.append('''on_predict'''   )

							def       __A (  self:   List[Any]		,     __A:   Any		,     __A:   List[str]		,     __A:   Union[str, Any]		,     **__A:   int   )    ->				str:
												self.events.append('''on_save'''   )

							def       __A (  self:   Union[str, Any]		,     __A:   str		,     __A:   Dict		,     __A:   Any		,     **__A:   Any   )    ->				Optional[Any]:
												self.events.append('''on_log'''   )



							def       __A (  self:   List[str]		,     __A:   int		,     __A:   Tuple		,     __A:   str		,     **__A:   Union[str, Any]   )    ->				List[Any]:
												self.events.append('''on_prediction_step'''   )





@require_torch
class 						SCREAMING_SNAKE_CASE				( unittest.TestCase					):





							"""simple docstring"""

							def       __A (  self:   Tuple   )    ->				Union[str, Any]:
												_A								= tempfile.mkdtemp()

							def       __A (  self:   Optional[Any]   )    ->				Any:
												shutil.rmtree(self.output_dir   )

							def       __A (  self:   str		,     __A:   Any=0		,     __A:   List[Any]=0		,     __A:   Optional[Any]=64		,     __A:   List[Any]=64		,     __A:   Optional[Any]=None		,     __A:   int=False		,     **__A:   List[Any]   )    ->				Union[str, Any]:
												_A								= RegressionDataset(length=lowerCAmelCase_   )
												_A								= RegressionDataset(length=lowerCAmelCase_   )
												_A								= RegressionModelConfig(a=lowerCAmelCase_		,     b=lowerCAmelCase_   )
												_A								= RegressionPreTrainedModel(lowerCAmelCase_   )

												_A								= 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:   List[str]		,     __A:   Dict		,     __A:   int   )    ->				Optional[Any]:
												self.assertEqual(len(lowerCAmelCase_   )		,     len(lowerCAmelCase_   )   )

												# Order doesn't matter
												_A								= sorted(lowerCAmelCase_		,     key=lambda __A   : cb.__name__ if isinstance(lowerCAmelCase_		,     lowerCAmelCase_   ) else cb.__class__.__name__   )
												_A								= sorted(lowerCAmelCase_		,     key=lambda __A   : 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:   Union[str, Any]		,     __A:   Union[str, Any]   )    ->				Optional[Any]:
												_A								= ['''on_init_end''', '''on_train_begin''']
												_A								= 0
												_A								= len(trainer.get_eval_dataloader()   )
												_A								= ['''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:   Tuple   )    ->				List[str]:
												_A								= self.get_trainer()
												_A								= DEFAULT_CALLBACKS.copy() + [ProgressCallback]
												self.check_callbacks_equality(trainer.callback_handler.callbacks		,     lowerCAmelCase_   )

												# Callbacks passed at init are added to the default callbacks
												_A								= 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								= self.get_trainer(disable_tqdm=lowerCAmelCase_   )
												_A								= DEFAULT_CALLBACKS.copy() + [PrinterCallback]
												self.check_callbacks_equality(trainer.callback_handler.callbacks		,     lowerCAmelCase_   )

							def       __A (  self:   int   )    ->				List[Any]:
												_A								= DEFAULT_CALLBACKS.copy() + [ProgressCallback]
												_A								= 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								= self.get_trainer()
												_A								= 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								= self.get_trainer()
												_A								= trainer.callback_handler.callbacks[0]
												trainer.remove_callback(lowerCAmelCase_   )
												expected_callbacks.remove(lowerCAmelCase_   )
												self.check_callbacks_equality(trainer.callback_handler.callbacks		,     lowerCAmelCase_   )

												_A								= self.get_trainer()
												_A								= trainer.callback_handler.callbacks[0]
												_A								= 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:   List[Any]   )    ->				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								= self.get_trainer(callbacks=[MyTestTrainerCallback]   )
												trainer.train()
												_A								= trainer.callback_handler.callbacks[-2].events
												self.assertEqual(lowerCAmelCase_		,     self.get_expected_events(lowerCAmelCase_   )   )

												# Independent log/save/eval
												_A								= self.get_trainer(callbacks=[MyTestTrainerCallback]		,     logging_steps=5   )
												trainer.train()
												_A								= trainer.callback_handler.callbacks[-2].events
												self.assertEqual(lowerCAmelCase_		,     self.get_expected_events(lowerCAmelCase_   )   )

												_A								= self.get_trainer(callbacks=[MyTestTrainerCallback]		,     save_steps=5   )
												trainer.train()
												_A								= trainer.callback_handler.callbacks[-2].events
												self.assertEqual(lowerCAmelCase_		,     self.get_expected_events(lowerCAmelCase_   )   )

												_A								= self.get_trainer(callbacks=[MyTestTrainerCallback]		,     eval_steps=5		,     evaluation_strategy='''steps'''   )
												trainer.train()
												_A								= trainer.callback_handler.callbacks[-2].events
												self.assertEqual(lowerCAmelCase_		,     self.get_expected_events(lowerCAmelCase_   )   )

												_A								= self.get_trainer(callbacks=[MyTestTrainerCallback]		,     evaluation_strategy='''epoch'''   )
												trainer.train()
												_A								= trainer.callback_handler.callbacks[-2].events
												self.assertEqual(lowerCAmelCase_		,     self.get_expected_events(lowerCAmelCase_   )   )

												# A bit of everything
												_A								= self.get_trainer(
												    callbacks=[MyTestTrainerCallback]		,     logging_steps=3		,     save_steps=10		,     eval_steps=5		,     evaluation_strategy='''steps'''		,     )
												trainer.train()
												_A								= 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								= self.get_trainer(
																	    callbacks=[MyTestTrainerCallback, MyTestTrainerCallback]		,     )
																	assert str(lowerCAmelCase_   ) in warn_mock.call_args[0][0]











def      __A					(     _lowercase					,			_lowercase					,			_lowercase					,			_lowercase ):

					'''simple docstring'''







					_A							,_A								= len(_lowercase ), len(grid[0] )
					if (
					    min(_lowercase					,			_lowercase ) < 0
					    or row == row_length
					    or col == col_length
					    or (row, col) in visit
					    or grid[row][col] == 1
					):
										return 0
					if row == row_length - 1 and col == col_length - 1:
										return 1

					visit.add((row, col) )

					_A								= 0
					count += depth_first_search(_lowercase					,			row + 1					,			_lowercase					,			_lowercase )
					count += depth_first_search(_lowercase					,			row - 1					,			_lowercase					,			_lowercase )
					count += depth_first_search(_lowercase					,			_lowercase					,			col + 1					,			_lowercase )
					count += depth_first_search(_lowercase					,			_lowercase					,			col - 1					,			_lowercase )

					visit.remove((row, col) )
					return count


if __name__ == "__main__":
				import doctest

				doctest.testmod()



