




'''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       ( lowerCamelCase__				):






       def __init__(							self  ):



              """simple docstring"""







              lowerCamelCase_							=[]






       def      lowercase__     (							self,		lowerCAmelCase,		lowerCAmelCase,		lowerCAmelCase,		**lowerCAmelCase  ):



              """simple docstring"""







              self.events.append('''on_init_end'''  )






       def      lowercase__     (							self,		lowerCAmelCase,		lowerCAmelCase,		lowerCAmelCase,		**lowerCAmelCase  ):



              """simple docstring"""







              self.events.append('''on_train_begin'''  )






       def      lowercase__     (							self,		lowerCAmelCase,		lowerCAmelCase,		lowerCAmelCase,		**lowerCAmelCase  ):



              """simple docstring"""







              self.events.append('''on_train_end'''  )






       def      lowercase__     (							self,		lowerCAmelCase,		lowerCAmelCase,		lowerCAmelCase,		**lowerCAmelCase  ):



              """simple docstring"""







              self.events.append('''on_epoch_begin'''  )






       def      lowercase__     (							self,		lowerCAmelCase,		lowerCAmelCase,		lowerCAmelCase,		**lowerCAmelCase  ):



              """simple docstring"""







              self.events.append('''on_epoch_end'''  )






       def      lowercase__     (							self,		lowerCAmelCase,		lowerCAmelCase,		lowerCAmelCase,		**lowerCAmelCase  ):



              """simple docstring"""







              self.events.append('''on_step_begin'''  )






       def      lowercase__     (							self,		lowerCAmelCase,		lowerCAmelCase,		lowerCAmelCase,		**lowerCAmelCase  ):



              """simple docstring"""







              self.events.append('''on_step_end'''  )






       def      lowercase__     (							self,		lowerCAmelCase,		lowerCAmelCase,		lowerCAmelCase,		**lowerCAmelCase  ):



              """simple docstring"""







              self.events.append('''on_evaluate'''  )






       def      lowercase__     (							self,		lowerCAmelCase,		lowerCAmelCase,		lowerCAmelCase,		**lowerCAmelCase  ):



              """simple docstring"""







              self.events.append('''on_predict'''  )






       def      lowercase__     (							self,		lowerCAmelCase,		lowerCAmelCase,		lowerCAmelCase,		**lowerCAmelCase  ):



              """simple docstring"""







              self.events.append('''on_save'''  )






       def      lowercase__     (							self,		lowerCAmelCase,		lowerCAmelCase,		lowerCAmelCase,		**lowerCAmelCase  ):



              """simple docstring"""







              self.events.append('''on_log'''  )






       def      lowercase__     (							self,		lowerCAmelCase,		lowerCAmelCase,		lowerCAmelCase,		**lowerCAmelCase  ):



              """simple docstring"""







              self.events.append('''on_prediction_step'''  )





@require_torch
class   __UpperCamelCase       ( unittest.TestCase				):






       def      lowercase__     (							self  ):



              """simple docstring"""







              lowerCamelCase_							=tempfile.mkdtemp()






       def      lowercase__     (							self  ):



              """simple docstring"""







              shutil.rmtree(self.output_dir  )






       def      lowercase__     (							self,		lowerCAmelCase=0,		lowerCAmelCase=0,		lowerCAmelCase=64,		lowerCAmelCase=64,		lowerCAmelCase=None,		lowerCAmelCase=False,		**lowerCAmelCase  ):



              """simple docstring"""







              lowerCamelCase_							=RegressionDataset(length=lowerCAmelCase  )
              lowerCamelCase_							=RegressionDataset(length=lowerCAmelCase  )
              lowerCamelCase_							=RegressionModelConfig(a=lowerCAmelCase,		b=lowerCAmelCase  )
              lowerCamelCase_							=RegressionPreTrainedModel(lowerCAmelCase  )

              lowerCamelCase_							=TrainingArguments(self.output_dir,		disable_tqdm=lowerCAmelCase,		report_to=[],		**lowerCAmelCase  )
              return Trainer(
                  lowerCAmelCase,		lowerCAmelCase,		train_dataset=lowerCAmelCase,		eval_dataset=lowerCAmelCase,		callbacks=lowerCAmelCase,		)






       def      lowercase__     (							self,		lowerCAmelCase,		lowerCAmelCase  ):



              """simple docstring"""







              self.assertEqual(len(lowerCAmelCase  ),		len(lowerCAmelCase  )  )

              # Order doesn't matter
              lowerCamelCase_							=sorted(lowerCAmelCase,		key=lambda lowerCAmelCase  : cb.__name__ if isinstance(lowerCAmelCase,		lowerCAmelCase  ) else cb.__class__.__name__  )
              lowerCamelCase_							=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      lowercase__     (							self,		lowerCAmelCase  ):



              """simple docstring"""







              lowerCamelCase_							=['''on_init_end''', '''on_train_begin''']
              lowerCamelCase_							=0
              lowerCamelCase_							=len(trainer.get_eval_dataloader()  )
              lowerCamelCase_							=['''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      lowercase__     (							self  ):



              """simple docstring"""







              lowerCamelCase_							=self.get_trainer()
              lowerCamelCase_							=DEFAULT_CALLBACKS.copy() + [ProgressCallback]
              self.check_callbacks_equality(trainer.callback_handler.callbacks,		lowerCAmelCase  )

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






       def      lowercase__     (							self  ):



              """simple docstring"""







              lowerCamelCase_							=DEFAULT_CALLBACKS.copy() + [ProgressCallback]
              lowerCamelCase_							=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  )

              lowerCamelCase_							=self.get_trainer()
              lowerCamelCase_							=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
              lowerCamelCase_							=self.get_trainer()
              lowerCamelCase_							=trainer.callback_handler.callbacks[0]
              trainer.remove_callback(lowerCAmelCase  )
              expected_callbacks.remove(lowerCAmelCase  )
              self.check_callbacks_equality(trainer.callback_handler.callbacks,		lowerCAmelCase  )

              lowerCamelCase_							=self.get_trainer()
              lowerCamelCase_							=trainer.callback_handler.callbacks[0]
              lowerCamelCase_							=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      lowercase__     (							self  ):



              """simple docstring"""







              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  )

              lowerCamelCase_							=self.get_trainer(callbacks=[MyTestTrainerCallback]  )
              trainer.train()
              lowerCamelCase_							=trainer.callback_handler.callbacks[-2].events
              self.assertEqual(lowerCAmelCase,		self.get_expected_events(lowerCAmelCase  )  )

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

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

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

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

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








'''simple docstring'''
def 			a      (			__a   )  ->	"list[int]":



					'''simple docstring'''






					if upper_limit < 0:
										raise ValueError('''Limit for the Catalan sequence must be ≥ 0'''   )

					UpperCamelCase__   :Optional[Any]												= [0] * (upper_limit + 1)

					# Base case: C(0) = C(1) = 1
					UpperCamelCase__   :int												= 1
					if upper_limit > 0:
										UpperCamelCase__   :int												= 1

					# Recurrence relation: C(i) = sum(C(j).C(i-j-1)), from j = 0 to i
					for i in range(2 ,					upper_limit + 1   ):
										for j in range(__a   ):
															catalan_list[i] += catalan_list[j] * catalan_list[i - j - 1]

					return catalan_list


if __name__ == "__main__":
		print('''\n********* Catalan Numbers Using Dynamic Programming ************\n''')
		print('''\n*** Enter -1 at any time to quit ***''')
		print('''\nEnter the upper limit (≥ 0) for the Catalan number sequence: ''', end='''''')
		try:
				while True:
						__snake_case							      =     int(input().strip())
						if N < 0:
								print('''\n********* Goodbye!! ************''')
								break
						else:
								print(F"""The Catalan numbers from 0 through {N} are:""")
								print(catalan_numbers(N))
								print('''Try another upper limit for the sequence: ''', end='''''')
		except (NameError, ValueError):
				print('''\n********* Invalid input, goodbye! ************\n''')

		import doctest

		doctest.testmod()