


import re
import time
from typing import Optional

import IPython.display as disp

from ..trainer_callback import TrainerCallback
from ..trainer_utils import IntervalStrategy, has_length



def       _lowerCAmelCase    (				lowerCAmelCase_				:Union[str, Any]				)->int:
   '''simple docstring'''






   snake_case_            =       int(lowerCAmelCase_				)
   snake_case_     ,     snake_case_     ,     snake_case_            =       t // 3_600, (t // 60) % 60, t % 60
   return F'''{h}:{m:02d}:{s:02d}''' if h != 0 else F'''{m:02d}:{s:02d}'''



def       _lowerCAmelCase    (				lowerCAmelCase_				:Union[str, Any]		,    lowerCAmelCase_				:List[str]		,    lowerCAmelCase_				:Union[str, Any]		,    lowerCAmelCase_				:Any		,    lowerCAmelCase_				:Tuple=300				)->str:
   '''simple docstring'''






   return F'''
    <div>
      {prefix}
      <progress value=\'{value}\' max=\'{total}\' style=\'width:{width}px; height:20px; vertical-align: middle;\'></progress>
      {label}
    </div>
    '''



def       _lowerCAmelCase    (				lowerCAmelCase_				:Union[str, Any]				)->Optional[int]:
   '''simple docstring'''






   snake_case_            =       "<table border=\"1\" class=\"dataframe\">\n"
   html_code += """  <thead>\n <tr style="text-align: left;">\n"""
   for i in items[0]:
      html_code += F'''      <th>{i}</th>\n'''
   html_code += "    </tr>\n  </thead>\n  <tbody>\n"
   for line in items[1:]:
      html_code += "    <tr>\n"
      for elt in line:
         snake_case_            =       F'''{elt:.6f}''' if isinstance(lowerCAmelCase_		,    lowerCAmelCase_				) else str(lowerCAmelCase_				)
         html_code += F'''      <td>{elt}</td>\n'''
      html_code += "    </tr>\n"
   html_code += "  </tbody>\n</table><p>"
   return html_code


class      __lowerCAmelCase  :






  """simple docstring"""





  _SCREAMING_SNAKE_CASE		     =							5
  _SCREAMING_SNAKE_CASE		     =							0.2



  def __init__(  self							:							Optional[Any]     ,					_lowerCAmelCase							:							int     ,					_lowerCAmelCase							:							Optional[str] = None     ,					_lowerCAmelCase							:							bool = True     ,					_lowerCAmelCase							:							Optional["NotebookTrainingTracker"] = None     ,					_lowerCAmelCase							:							int = 3_0_0     ,					) ->			Optional[Any]:




     """simple docstring"""
     snake_case_            =       total
     snake_case_            =       "" if prefix is None else prefix
     snake_case_            =       leave
     snake_case_            =       parent
     snake_case_            =       width
     snake_case_            =       None
     snake_case_            =       None
     snake_case_            =       None



  def        lowerCAmelCase__	(  self							:							List[Any]     ,					_lowerCAmelCase							:							int     ,					_lowerCAmelCase							:							bool = False     ,					_lowerCAmelCase							:							str = None	) ->			Tuple:




     """simple docstring"""
     snake_case_            =       value
     if comment is not None:
        snake_case_            =       comment
     if self.last_value is None:
        snake_case_            =       snake_case_            =       time.time()
        snake_case_            =       snake_case_            =       value
        snake_case_            =       snake_case_            =       None
        snake_case_            =       self.warmup
        snake_case_            =       1
        self.update_bar(_lowerCAmelCase	)
     elif value <= self.last_value and not force_update:
        return
     elif force_update or self.first_calls > 0 or value >= min(self.last_value + self.wait_for     ,					self.total	):
        if self.first_calls > 0:
           self.first_calls -= 1
        snake_case_            =       time.time()
        snake_case_            =       current_time - self.start_time
        # We could have value = self.start_value if the update is called twixe with the same start value.
        if value > self.start_value:
           snake_case_            =       self.elapsed_time / (value - self.start_value)
        else:
           snake_case_            =       None
        if value >= self.total:
           snake_case_            =       self.total
           snake_case_            =       None
           if not self.leave:
              self.close()
        elif self.average_time_per_item is not None:
           snake_case_            =       self.average_time_per_item * (self.total - value)
        self.update_bar(_lowerCAmelCase	)
        snake_case_            =       value
        snake_case_            =       current_time
        if self.average_time_per_item is None:
           snake_case_            =       1
        else:
           snake_case_            =       max(int(self.update_every / self.average_time_per_item	)     ,					1	)



  def        lowerCAmelCase__	(  self							:							List[str]     ,					_lowerCAmelCase							:							Union[str, Any]     ,					_lowerCAmelCase							:							List[str]=None	) ->			Any:




     """simple docstring"""
     snake_case_            =       " " * (len(str(self.total	)	) - len(str(_lowerCAmelCase	)	)) + str(_lowerCAmelCase	)
     if self.elapsed_time is None:
        snake_case_            =       F'''[{spaced_value}/{self.total} : < :'''
     elif self.predicted_remaining is None:
        snake_case_            =       F'''[{spaced_value}/{self.total} {format_time(self.elapsed_time	)}'''
     else:
        snake_case_            =       (
            F'''[{spaced_value}/{self.total} {format_time(self.elapsed_time	)} <'''
            F''' {format_time(self.predicted_remaining	)}'''
        )
        self.label += F''', {1/self.average_time_per_item:.2f} it/s'''
     self.label += "]" if self.comment is None or len(self.comment	) == 0 else F''', {self.comment}]'''
     self.display()



  def        lowerCAmelCase__	(  self							:							str	) ->			Dict:




     """simple docstring"""
     snake_case_            =       html_progress_bar(self.value     ,					self.total     ,					self.prefix     ,					self.label     ,					self.width	)
     if self.parent is not None:
        # If this is a child bar, the parent will take care of the display.
        self.parent.display()
        return
     if self.output is None:
        snake_case_            =       disp.display(disp.HTML(self.html_code	)     ,					display_id=_lowerCAmelCase	)
     else:
        self.output.update(disp.HTML(self.html_code	)	)



  def        lowerCAmelCase__	(  self							:							Union[str, Any]	) ->			Tuple:




     """simple docstring"""
     if self.parent is None and self.output is not None:
        self.output.update(disp.HTML(""	)	)






class      __lowerCAmelCase  (			a       ):






  """simple docstring"""





  def __init__(  self							:							int     ,					_lowerCAmelCase							:							Optional[int]     ,					_lowerCAmelCase							:							List[str]=None	) ->			List[Any]:




     """simple docstring"""
     super().__init__(_lowerCAmelCase	)
     snake_case_            =       None if column_names is None else [column_names]
     snake_case_            =       None



  def        lowerCAmelCase__	(  self							:							int	) ->			List[str]:




     """simple docstring"""
     snake_case_            =       html_progress_bar(self.value     ,					self.total     ,					self.prefix     ,					self.label     ,					self.width	)
     if self.inner_table is not None:
        self.html_code += text_to_html_table(self.inner_table	)
     if self.child_bar is not None:
        self.html_code += self.child_bar.html_code
     if self.output is None:
        snake_case_            =       disp.display(disp.HTML(self.html_code	)     ,					display_id=_lowerCAmelCase	)
     else:
        self.output.update(disp.HTML(self.html_code	)	)



  def        lowerCAmelCase__	(  self							:							Any     ,					_lowerCAmelCase							:							Dict	) ->			List[str]:




     """simple docstring"""
     if self.inner_table is None:
        snake_case_            =       [list(values.keys()	), list(values.values()	)]
     else:
        snake_case_            =       self.inner_table[0]
        if len(self.inner_table	) == 1:
           # We give a chance to update the column names at the first iteration
           for key in values.keys():
              if key not in columns:
                 columns.append(_lowerCAmelCase	)
           snake_case_            =       columns
        self.inner_table.append([values[c] for c in columns]	)



  def        lowerCAmelCase__	(  self							:							List[Any]     ,					_lowerCAmelCase							:							Tuple     ,					_lowerCAmelCase							:							Dict=None     ,					_lowerCAmelCase							:							List[Any]=3_0_0	) ->			Tuple:




     """simple docstring"""
     snake_case_            =       NotebookProgressBar(_lowerCAmelCase     ,					prefix=_lowerCAmelCase     ,					parent=self     ,					width=_lowerCAmelCase	)
     return self.child_bar



  def        lowerCAmelCase__	(  self							:							Union[str, Any]	) ->			Optional[Any]:




     """simple docstring"""
     snake_case_            =       None
     self.display()






class      __lowerCAmelCase  (			a       ):






  """simple docstring"""





  def __init__(  self							:							str	) ->			Optional[int]:




     """simple docstring"""
     snake_case_            =       None
     snake_case_            =       None
     snake_case_            =       False



  def        lowerCAmelCase__	(  self							:							Dict     ,					_lowerCAmelCase							:							Dict     ,					_lowerCAmelCase							:							int     ,					_lowerCAmelCase							:							Optional[int]     ,					**_lowerCAmelCase							:							List[Any]	) ->			Union[str, Any]:




     """simple docstring"""
     snake_case_            =       "Epoch" if args.evaluation_strategy == IntervalStrategy.EPOCH else "Step"
     snake_case_            =       0
     snake_case_            =       0
     snake_case_            =       [self.first_column] + ["Training Loss"]
     if args.evaluation_strategy != IntervalStrategy.NO:
        column_names.append("Validation Loss"	)
     snake_case_            =       NotebookTrainingTracker(state.max_steps     ,					_lowerCAmelCase	)



  def        lowerCAmelCase__	(  self							:							Dict     ,					_lowerCAmelCase							:							Optional[Any]     ,					_lowerCAmelCase							:							Optional[Any]     ,					_lowerCAmelCase							:							Union[str, Any]     ,					**_lowerCAmelCase							:							Optional[Any]	) ->			int:




     """simple docstring"""
     snake_case_            =       int(state.epoch	) if int(state.epoch	) == state.epoch else F'''{state.epoch:.2f}'''
     self.training_tracker.update(
         state.global_step + 1     ,					comment=F'''Epoch {epoch}/{state.num_train_epochs}'''     ,					force_update=self._force_next_update     ,					)
     snake_case_            =       False



  def        lowerCAmelCase__	(  self							:							List[Any]     ,					_lowerCAmelCase							:							Optional[Any]     ,					_lowerCAmelCase							:							List[str]     ,					_lowerCAmelCase							:							List[str]     ,					_lowerCAmelCase							:							Tuple=None     ,					**_lowerCAmelCase							:							List[str]	) ->			Tuple:




     """simple docstring"""
     if not has_length(_lowerCAmelCase	):
        return
     if self.prediction_bar is None:
        if self.training_tracker is not None:
           snake_case_            =       self.training_tracker.add_child(len(_lowerCAmelCase	)	)
        else:
           snake_case_            =       NotebookProgressBar(len(_lowerCAmelCase	)	)
        self.prediction_bar.update(1	)
     else:
        self.prediction_bar.update(self.prediction_bar.value + 1	)



  def        lowerCAmelCase__	(  self							:							Tuple     ,					_lowerCAmelCase							:							Optional[Any]     ,					_lowerCAmelCase							:							List[Any]     ,					_lowerCAmelCase							:							Dict     ,					**_lowerCAmelCase							:							Tuple	) ->			Optional[int]:




     """simple docstring"""
     if self.prediction_bar is not None:
        self.prediction_bar.close()
     snake_case_            =       None



  def        lowerCAmelCase__	(  self							:							Union[str, Any]     ,					_lowerCAmelCase							:							str     ,					_lowerCAmelCase							:							Tuple     ,					_lowerCAmelCase							:							Optional[Any]     ,					_lowerCAmelCase							:							Tuple=None     ,					**_lowerCAmelCase							:							Optional[Any]	) ->			Union[str, Any]:




     """simple docstring"""
     # Only for when there is no evaluation
     if args.evaluation_strategy == IntervalStrategy.NO and "loss" in logs:
        snake_case_            =       {"Training Loss": logs["loss"]}
        # First column is necessarily Step sine we're not in epoch eval strategy
        snake_case_            =       state.global_step
        self.training_tracker.write_line(_lowerCAmelCase	)



  def        lowerCAmelCase__	(  self							:							Union[str, Any]     ,					_lowerCAmelCase							:							Optional[int]     ,					_lowerCAmelCase							:							Optional[int]     ,					_lowerCAmelCase							:							Optional[int]     ,					_lowerCAmelCase							:							List[str]=None     ,					**_lowerCAmelCase							:							Union[str, Any]	) ->			List[Any]:




     """simple docstring"""
     if self.training_tracker is not None:
        snake_case_            =       {"Training Loss": "No log", "Validation Loss": "No log"}
        for log in reversed(state.log_history	):
           if "loss" in log:
              snake_case_            =       log["loss"]
              break

        if self.first_column == "Epoch":
           snake_case_            =       int(state.epoch	)
        else:
           snake_case_            =       state.global_step
        snake_case_            =       "eval"
        for k in metrics:
           if k.endswith("_loss"	):
              snake_case_            =       re.sub(R"\_loss$"     ,					""     ,					_lowerCAmelCase	)
        snake_case_            =       metrics.pop("total_flos"     ,					_lowerCAmelCase	)
        snake_case_            =       metrics.pop("epoch"     ,					_lowerCAmelCase	)
        snake_case_            =       metrics.pop(F'''{metric_key_prefix}_runtime'''     ,					_lowerCAmelCase	)
        snake_case_            =       metrics.pop(F'''{metric_key_prefix}_samples_per_second'''     ,					_lowerCAmelCase	)
        snake_case_            =       metrics.pop(F'''{metric_key_prefix}_steps_per_second'''     ,					_lowerCAmelCase	)
        snake_case_            =       metrics.pop(F'''{metric_key_prefix}_jit_compilation_time'''     ,					_lowerCAmelCase	)
        for k, v in metrics.items():
           if k == F'''{metric_key_prefix}_loss''':
              snake_case_            =       v
           else:
              snake_case_            =       k.split("_"	)
              snake_case_            =       " ".join([part.capitalize() for part in splits[1:]]	)
              snake_case_            =       v
        self.training_tracker.write_line(_lowerCAmelCase	)
        self.training_tracker.remove_child()
        snake_case_            =       None
        # Evaluation takes a long time so we should force the next update.
        snake_case_            =       True



  def        lowerCAmelCase__	(  self							:							Optional[Any]     ,					_lowerCAmelCase							:							Dict     ,					_lowerCAmelCase							:							Optional[Any]     ,					_lowerCAmelCase							:							int     ,					**_lowerCAmelCase							:							Tuple	) ->			Union[str, Any]:




     """simple docstring"""
     self.training_tracker.update(
         state.global_step     ,					comment=F'''Epoch {int(state.epoch	)}/{state.num_train_epochs}'''     ,					force_update=_lowerCAmelCase	)
     snake_case_            =       None








from math import factorial



def       _lowerCAmelCase    (				lowerCAmelCase_				:int = 20				)->int:
   '''simple docstring'''






   snake_case_            =       2 * n  # middle entry of odd rows starting at row 3 is the solution for n = 1,
   # 2, 3,...
   snake_case_            =       n // 2

   return int(factorial(lowerCAmelCase_				) / (factorial(lowerCAmelCase_				) * factorial(n - k				))				)


if __name__ == "__main__":
   import sys

   if len(sys.argv) == 1:
      print(solution(20))
   else:
      try:
         SCREAMING_SNAKE_CASE						:Any			=  int(sys.argv[1])
         print(solution(n))
      except ValueError:
         print('''Invalid entry - please enter a number.''')




