






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





	"""simple docstring"""




	def __init__(self				):
		A_		:    Optional[int]						     = []





	def  lowerCamelCase(self  ,  lowerCAmelCase_  ,  lowerCAmelCase_  ,  lowerCAmelCase_  ,  **lowerCAmelCase_				):
		self.events.append("""on_init_end"""				)





	def  lowerCamelCase(self  ,  lowerCAmelCase_  ,  lowerCAmelCase_  ,  lowerCAmelCase_  ,  **lowerCAmelCase_				):
		self.events.append("""on_train_begin"""				)





	def  lowerCamelCase(self  ,  lowerCAmelCase_  ,  lowerCAmelCase_  ,  lowerCAmelCase_  ,  **lowerCAmelCase_				):
		self.events.append("""on_train_end"""				)





	def  lowerCamelCase(self  ,  lowerCAmelCase_  ,  lowerCAmelCase_  ,  lowerCAmelCase_  ,  **lowerCAmelCase_				):
		self.events.append("""on_epoch_begin"""				)





	def  lowerCamelCase(self  ,  lowerCAmelCase_  ,  lowerCAmelCase_  ,  lowerCAmelCase_  ,  **lowerCAmelCase_				):
		self.events.append("""on_epoch_end"""				)





	def  lowerCamelCase(self  ,  lowerCAmelCase_  ,  lowerCAmelCase_  ,  lowerCAmelCase_  ,  **lowerCAmelCase_				):
		self.events.append("""on_step_begin"""				)





	def  lowerCamelCase(self  ,  lowerCAmelCase_  ,  lowerCAmelCase_  ,  lowerCAmelCase_  ,  **lowerCAmelCase_				):
		self.events.append("""on_step_end"""				)





	def  lowerCamelCase(self  ,  lowerCAmelCase_  ,  lowerCAmelCase_  ,  lowerCAmelCase_  ,  **lowerCAmelCase_				):
		self.events.append("""on_evaluate"""				)





	def  lowerCamelCase(self  ,  lowerCAmelCase_  ,  lowerCAmelCase_  ,  lowerCAmelCase_  ,  **lowerCAmelCase_				):
		self.events.append("""on_predict"""				)





	def  lowerCamelCase(self  ,  lowerCAmelCase_  ,  lowerCAmelCase_  ,  lowerCAmelCase_  ,  **lowerCAmelCase_				):
		self.events.append("""on_save"""				)





	def  lowerCamelCase(self  ,  lowerCAmelCase_  ,  lowerCAmelCase_  ,  lowerCAmelCase_  ,  **lowerCAmelCase_				):
		self.events.append("""on_log"""				)





	def  lowerCamelCase(self  ,  lowerCAmelCase_  ,  lowerCAmelCase_  ,  lowerCAmelCase_  ,  **lowerCAmelCase_				):
		self.events.append("""on_prediction_step"""				)






@require_torch
class   SCREAMING_SNAKE_CASE	(					unittest.TestCase    ):





	"""simple docstring"""




	def  lowerCamelCase(self				):
		A_		:    Optional[int]						     = tempfile.mkdtemp()





	def  lowerCamelCase(self				):
		shutil.rmtree(self.output_dir				)





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

		A_		:    List[Any]						     = TrainingArguments(self.output_dir  ,  disable_tqdm=lowerCAmelCase_  ,  report_to=[]  ,  **lowerCAmelCase_				)
		return Trainer(
		    lowerCAmelCase_  ,  lowerCAmelCase_  ,  train_dataset=lowerCAmelCase_  ,  eval_dataset=lowerCAmelCase_  ,  callbacks=lowerCAmelCase_  ,  )





	def  lowerCamelCase(self  ,  lowerCAmelCase_  ,  lowerCAmelCase_				):
		self.assertEqual(len(lowerCAmelCase_				)  ,  len(lowerCAmelCase_				)				)

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

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





	def  lowerCamelCase(self				):
		A_		:    List[str]						     = DEFAULT_CALLBACKS.copy() + [ProgressCallback]
		A_		:    List[str]						     = 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_		:    Tuple						     = 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_		:    Any						     = self.get_trainer()
		A_		:    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[Any]						     = self.get_trainer()
		A_		:    Tuple						     = trainer.callback_handler.callbacks[0]
		A_		:    Dict						     = 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  lowerCamelCase(self				):
		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_		:    List[str]						     = 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_		:    Optional[int]						     = self.get_trainer(callbacks=[MyTestTrainerCallback]  ,  logging_steps=5				)
		trainer.train()
		A_		:    Dict						     = trainer.callback_handler.callbacks[-2].events
		self.assertEqual(lowerCAmelCase_  ,  self.get_expected_events(lowerCAmelCase_				)				)

		A_		:    Optional[Any]						     = 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_		:    str						     = trainer.callback_handler.callbacks[-2].events
		self.assertEqual(lowerCAmelCase_  ,  self.get_expected_events(lowerCAmelCase_				)				)

		A_		:    Tuple						     = self.get_trainer(callbacks=[MyTestTrainerCallback]  ,  evaluation_strategy="""epoch"""				)
		trainer.train()
		A_		:    List[Any]						     = trainer.callback_handler.callbacks[-2].events
		self.assertEqual(lowerCAmelCase_  ,  self.get_expected_events(lowerCAmelCase_				)				)

		# A bit of everything
		A_		:    Dict						     = self.get_trainer(
		    callbacks=[MyTestTrainerCallback]  ,  logging_steps=3  ,  save_steps=10  ,  eval_steps=5  ,  evaluation_strategy="""steps"""  ,  )
		trainer.train()
		A_		:    Optional[Any]						     = 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"""
from __future__ import annotations

from decimal import Decimal
from math import *  # noqa: F403

from sympy import diff






def       __UpperCamelCase						(		snake_case__ , snake_case__ , snake_case__ = 10**-10       ):
	A_		:    Tuple						     = a
	while True:
		A_		:    List[str]						     = Decimal(snake_case__       ) - (
		    Decimal(eval(snake_case__       )       ) / Decimal(eval(str(diff(snake_case__       )       )       )       )  # noqa: S307
		)
		# This number dictates the accuracy of the answer
		if abs(eval(snake_case__       )       ) < precision:  # noqa: S307
			return float(snake_case__       )


# Let's Execute
if __name__ == "__main__":
							# Find root of trigonometric function
							# Find value of pi
							print(F'The root of sin(x) = 0 is {newton_raphson("sin(x)", 2)}')
							# Find root of polynomial
							print(F'The root of x**2 - 5*x + 2 = 0 is {newton_raphson("x**2 - 5*x + 2", 0.4)}')
							# Find Square Root of 5
							print(F'The root of log(x) - 1 = 0 is {newton_raphson("log(x) - 1", 2)}')
							# Exponential Roots
							print(F'The root of exp(x) - 1 = 0 is {newton_raphson("exp(x) - 1", 0)}')

