




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__     ):

    '''simple docstring'''



    def __init__(    self     )     ->      Any:
           lowerCamelCase   :      Optional[int]			 =					[]







    def     _lowercase     (    self     ,  UpperCamelCase__     ,  UpperCamelCase__     ,  UpperCamelCase__     ,  **UpperCamelCase__     )     ->      Tuple:
           self.events.append("on_init_end"     )







    def     _lowercase     (    self     ,  UpperCamelCase__     ,  UpperCamelCase__     ,  UpperCamelCase__     ,  **UpperCamelCase__     )     ->      List[str]:
           self.events.append("on_train_begin"     )







    def     _lowercase     (    self     ,  UpperCamelCase__     ,  UpperCamelCase__     ,  UpperCamelCase__     ,  **UpperCamelCase__     )     ->      List[str]:
           self.events.append("on_train_end"     )







    def     _lowercase     (    self     ,  UpperCamelCase__     ,  UpperCamelCase__     ,  UpperCamelCase__     ,  **UpperCamelCase__     )     ->      int:
           self.events.append("on_epoch_begin"     )







    def     _lowercase     (    self     ,  UpperCamelCase__     ,  UpperCamelCase__     ,  UpperCamelCase__     ,  **UpperCamelCase__     )     ->      List[str]:
           self.events.append("on_epoch_end"     )







    def     _lowercase     (    self     ,  UpperCamelCase__     ,  UpperCamelCase__     ,  UpperCamelCase__     ,  **UpperCamelCase__     )     ->      List[Any]:
           self.events.append("on_step_begin"     )







    def     _lowercase     (    self     ,  UpperCamelCase__     ,  UpperCamelCase__     ,  UpperCamelCase__     ,  **UpperCamelCase__     )     ->      Tuple:
           self.events.append("on_step_end"     )







    def     _lowercase     (    self     ,  UpperCamelCase__     ,  UpperCamelCase__     ,  UpperCamelCase__     ,  **UpperCamelCase__     )     ->      Dict:
           self.events.append("on_evaluate"     )







    def     _lowercase     (    self     ,  UpperCamelCase__     ,  UpperCamelCase__     ,  UpperCamelCase__     ,  **UpperCamelCase__     )     ->      Dict:
           self.events.append("on_predict"     )







    def     _lowercase     (    self     ,  UpperCamelCase__     ,  UpperCamelCase__     ,  UpperCamelCase__     ,  **UpperCamelCase__     )     ->      Optional[int]:
           self.events.append("on_save"     )







    def     _lowercase     (    self     ,  UpperCamelCase__     ,  UpperCamelCase__     ,  UpperCamelCase__     ,  **UpperCamelCase__     )     ->      str:
           self.events.append("on_log"     )







    def     _lowercase     (    self     ,  UpperCamelCase__     ,  UpperCamelCase__     ,  UpperCamelCase__     ,  **UpperCamelCase__     )     ->      Union[str, Any]:
           self.events.append("on_prediction_step"     )




@require_torch
class 		UpperCamelCase__	(unittest.TestCase     ):

    '''simple docstring'''



    def     _lowercase     (    self     )     ->      Optional[int]:
           lowerCamelCase   :      int			 =					tempfile.mkdtemp()







    def     _lowercase     (    self     )     ->      str:
           shutil.rmtree(self.output_dir     )







    def     _lowercase     (    self     ,  UpperCamelCase__=0     ,  UpperCamelCase__=0     ,  UpperCamelCase__=64     ,  UpperCamelCase__=64     ,  UpperCamelCase__=None     ,  UpperCamelCase__=False     ,  **UpperCamelCase__     )     ->      Optional[Any]:
           # 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.
           lowerCamelCase   :      Dict			 =					RegressionDataset(length=UpperCamelCase__     )
           lowerCamelCase   :      str			 =					RegressionDataset(length=UpperCamelCase__     )
           lowerCamelCase   :      List[str]			 =					RegressionModelConfig(a=UpperCamelCase__     ,  b=UpperCamelCase__     )
           lowerCamelCase   :      List[Any]			 =					RegressionPreTrainedModel(UpperCamelCase__     )

           lowerCamelCase   :      Optional[int]			 =					TrainingArguments(self.output_dir     ,  disable_tqdm=UpperCamelCase__     ,  report_to=[]     ,  **UpperCamelCase__     )
           return Trainer(
               UpperCamelCase__     ,  UpperCamelCase__     ,  train_dataset=UpperCamelCase__     ,  eval_dataset=UpperCamelCase__     ,  callbacks=UpperCamelCase__     ,  )







    def     _lowercase     (    self     ,  UpperCamelCase__     ,  UpperCamelCase__     )     ->      Optional[int]:
           self.assertEqual(len(UpperCamelCase__     )     ,  len(UpperCamelCase__     )     )

           # Order doesn't matter
           lowerCamelCase   :      Dict			 =					sorted(UpperCamelCase__     ,  key=lambda UpperCamelCase__     : cb.__name__ if isinstance(UpperCamelCase__     ,  UpperCamelCase__     ) else cb.__class__.__name__     )
           lowerCamelCase   :      List[str]			 =					sorted(UpperCamelCase__     ,  key=lambda UpperCamelCase__     : cb.__name__ if isinstance(UpperCamelCase__     ,  UpperCamelCase__     ) else cb.__class__.__name__     )

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







    def     _lowercase     (    self     ,  UpperCamelCase__     )     ->      Optional[Any]:
           lowerCamelCase   :      Tuple			 =					["on_init_end", "on_train_begin"]
           lowerCamelCase   :      Union[str, Any]			 =					0
           lowerCamelCase   :      Dict			 =					len(trainer.get_eval_dataloader()     )
           lowerCamelCase   :      Union[str, Any]			 =					["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(UpperCamelCase__     ):
                         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     )     ->      List[str]:
           lowerCamelCase   :      List[str]			 =					self.get_trainer()
           lowerCamelCase   :      str			 =					DEFAULT_CALLBACKS.copy() + [ProgressCallback]
           self.check_callbacks_equality(trainer.callback_handler.callbacks     ,  UpperCamelCase__     )

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

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







    def     _lowercase     (    self     )     ->      List[str]:
           lowerCamelCase   :      List[Any]			 =					DEFAULT_CALLBACKS.copy() + [ProgressCallback]
           lowerCamelCase   :      Optional[int]			 =					self.get_trainer()

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

           lowerCamelCase   :      str			 =					self.get_trainer()
           lowerCamelCase   :      Tuple			 =					trainer.pop_callback(UpperCamelCase__     )
           self.assertEqual(cb.__class__     ,  UpperCamelCase__     )
           self.check_callbacks_equality(trainer.callback_handler.callbacks     ,  UpperCamelCase__     )

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

           # We can also add, pop, or remove by instance
           lowerCamelCase   :      Optional[Any]			 =					self.get_trainer()
           lowerCamelCase   :      Optional[int]			 =					trainer.callback_handler.callbacks[0]
           trainer.remove_callback(UpperCamelCase__     )
           expected_callbacks.remove(UpperCamelCase__     )
           self.check_callbacks_equality(trainer.callback_handler.callbacks     ,  UpperCamelCase__     )

           lowerCamelCase   :      Tuple			 =					self.get_trainer()
           lowerCamelCase   :      Tuple			 =					trainer.callback_handler.callbacks[0]
           lowerCamelCase   :      List[str]			 =					trainer.pop_callback(UpperCamelCase__     )
           self.assertEqual(UpperCamelCase__     ,  UpperCamelCase__     )
           self.check_callbacks_equality(trainer.callback_handler.callbacks     ,  UpperCamelCase__     )

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







    def     _lowercase     (    self     )     ->      List[str]:
           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=UpperCamelCase__     )

           lowerCamelCase   :      List[str]			 =					self.get_trainer(callbacks=[MyTestTrainerCallback]     )
           trainer.train()
           lowerCamelCase   :      Any			 =					trainer.callback_handler.callbacks[-2].events
           self.assertEqual(UpperCamelCase__     ,  self.get_expected_events(UpperCamelCase__     )     )

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

           lowerCamelCase   :      Dict			 =					self.get_trainer(callbacks=[MyTestTrainerCallback]     ,  save_steps=5     )
           trainer.train()
           lowerCamelCase   :      str			 =					trainer.callback_handler.callbacks[-2].events
           self.assertEqual(UpperCamelCase__     ,  self.get_expected_events(UpperCamelCase__     )     )

           lowerCamelCase   :      Union[str, Any]			 =					self.get_trainer(callbacks=[MyTestTrainerCallback]     ,  eval_steps=5     ,  evaluation_strategy="steps"     )
           trainer.train()
           lowerCamelCase   :      Dict			 =					trainer.callback_handler.callbacks[-2].events
           self.assertEqual(UpperCamelCase__     ,  self.get_expected_events(UpperCamelCase__     )     )

           lowerCamelCase   :      int			 =					self.get_trainer(callbacks=[MyTestTrainerCallback]     ,  evaluation_strategy="epoch"     )
           trainer.train()
           lowerCamelCase   :      List[str]			 =					trainer.callback_handler.callbacks[-2].events
           self.assertEqual(UpperCamelCase__     ,  self.get_expected_events(UpperCamelCase__     )     )

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

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












from __future__ import annotations

lowerCamelCase__ :   Optional[int]					=							[-10, -5, 0, 5, 5.1, 11, 13, 21, 3, 4, -21, -10, -5, -1, 0]
lowerCamelCase__ :   List[Any]					=							[-5, 0, 5, 5.1, 11, 13, 21, -1, 4, -1, -10, -5, -1, 0, -1]

def 					UpperCAmelCase_							(      __UpperCAmelCase						:	list[float]							)					-> list[float]:
      SCREAMING_SNAKE_CASE_							=			[]
      SCREAMING_SNAKE_CASE_							=			len(__UpperCAmelCase							)

      for i in range(__UpperCAmelCase							):
            SCREAMING_SNAKE_CASE_							=			-1
            for j in range(i + 1			,			__UpperCAmelCase							):
                  if arr[i] < arr[j]:
                        SCREAMING_SNAKE_CASE_							=			arr[j]
                        break
            result.append(__UpperCAmelCase							)
      return result

def 					UpperCAmelCase_							(      __UpperCAmelCase						:	list[float]							)					-> list[float]:
      SCREAMING_SNAKE_CASE_							=			[]
      for i, outer in enumerate(__UpperCAmelCase							):
            SCREAMING_SNAKE_CASE_							=			-1
            for inner in arr[i + 1 :]:
                  if outer < inner:
                        SCREAMING_SNAKE_CASE_							=			inner
                        break
            result.append(__UpperCAmelCase							)
      return result

def 					UpperCAmelCase_							(      __UpperCAmelCase						:	list[float]							)					-> list[float]:
      SCREAMING_SNAKE_CASE_							=			len(__UpperCAmelCase							)
      SCREAMING_SNAKE_CASE_							=			[]
      SCREAMING_SNAKE_CASE_							=			[-1] * arr_size

      for index in reversed(range(__UpperCAmelCase							)							):
            if stack:
                  while stack[-1] <= arr[index]:
                        stack.pop()
                        if not stack:
                              break
            if stack:
                  SCREAMING_SNAKE_CASE_							=			stack[-1]
            stack.append(arr[index]							)
      return result


if __name__ == "__main__":
   from doctest import testmod
   from timeit import timeit

   testmod()
   print(next_greatest_element_slow(arr))
   print(next_greatest_element_fast(arr))
   print(next_greatest_element(arr))

   lowerCamelCase__ :   List[str]					=							(
       'from __main__ import arr, next_greatest_element_slow, '
       'next_greatest_element_fast, next_greatest_element'
   )
   print(
       'next_greatest_element_slow():',
       timeit('next_greatest_element_slow(arr)', setup=setup),
   )
   print(
       'next_greatest_element_fast():',
       timeit('next_greatest_element_fast(arr)', setup=setup),
   )
   print(
       '     next_greatest_element():',
       timeit('next_greatest_element(arr)', setup=setup),
   )