
import contextlib
import importlib
import io
import unittest

import transformers

# Try to import everything from transformers to ensure every object can be loaded.
from transformers import *  # noqa F406
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, require_tf, require_torch
from transformers.utils import ContextManagers, find_labels, is_flax_available, is_tf_available, is_torch_available


if is_torch_available():
		from transformers import BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification

if is_tf_available():
		from transformers import TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification

if is_flax_available():
		from transformers import FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification


lowercase   =	DUMMY_UNKNOWN_IDENTIFIER
# An actual model hosted on huggingface.co

lowercase   =	"main"
# Default branch name
lowercase   =	"f2c752cfc5c0ab6f4bdec59acea69eefbee381c2"
# One particular commit (not the top of `main`)
lowercase   =	"aaaaaaa"
# This commit does not exist, so we should 404.

lowercase   =	"d9e9f15bc825e4b2c9249e9578f884bbcb5e3684"
# Sha-1 of config.json on the top of `main`, for checking purposes
lowercase   =	"4b243c475af8d0a7754e87d7d096c92e5199ec2fe168a2ee7998e3b8e9bcb1d3"



@contextlib.contextmanager
def   __lowerCAmelCase    (				)	->     List[Any]:
							print("""Welcome!"""							)
							yield
							print("""Bye!"""							)



@contextlib.contextmanager
def   __lowerCAmelCase    (				)	->     Dict:
							print("""Bonjour!"""							)
							yield
							print("""Au revoir!"""							)





class    __A(					unittest.TestCase							):

					def  lowercase__   (						self       :  List[Any] ):
												assert transformers.__spec__ is not None
												assert importlib.util.find_spec("""transformers""" ) is not None





class    __A(					unittest.TestCase							):

					@unittest.mock.patch("""sys.stdout""" ,       new_callable=io.StringIO )
					def  lowercase__   (						self       :  Any ,       __UpperCamelCase       :  Tuple ):
												with ContextManagers([] ):
																			print("""Transformers are awesome!""" )
												# The print statement adds a new line at the end of the output
												self.assertEqual(mock_stdout.getvalue() ,       """Transformers are awesome!\n""" )

					@unittest.mock.patch("""sys.stdout""" ,       new_callable=io.StringIO )
					def  lowercase__   (						self       :  int ,       __UpperCamelCase       :  str ):
												with ContextManagers([context_en()] ):
																			print("""Transformers are awesome!""" )
												# The output should be wrapped with an English welcome and goodbye
												self.assertEqual(mock_stdout.getvalue() ,       """Welcome!\nTransformers are awesome!\nBye!\n""" )

					@unittest.mock.patch("""sys.stdout""" ,       new_callable=io.StringIO )
					def  lowercase__   (						self       :  Dict ,       __UpperCamelCase       :  Union[str, Any] ):
												with ContextManagers([context_fr(), context_en()] ):
																			print("""Transformers are awesome!""" )
												# The output should be wrapped with an English and French welcome and goodbye
												self.assertEqual(mock_stdout.getvalue() ,       """Bonjour!\nWelcome!\nTransformers are awesome!\nBye!\nAu revoir!\n""" )

					@require_torch
					def  lowercase__   (						self       :  Any ):
												self.assertEqual(find_labels(a_ ) ,       ["""labels"""] )
												self.assertEqual(find_labels(a_ ) ,       ["""labels""", """next_sentence_label"""] )
												self.assertEqual(find_labels(a_ ) ,       ["""start_positions""", """end_positions"""] )





												class    __A(					UpperCAmelCase							):
																	pass
												self.assertEqual(find_labels(a_ ) ,       ["""labels"""] )

					@require_tf
					def  lowercase__   (						self       :  Union[str, Any] ):
												self.assertEqual(find_labels(a_ ) ,       ["""labels"""] )
												self.assertEqual(find_labels(a_ ) ,       ["""labels""", """next_sentence_label"""] )
												self.assertEqual(find_labels(a_ ) ,       ["""start_positions""", """end_positions"""] )





												class    __A(					UpperCAmelCase							):
																	pass
												self.assertEqual(find_labels(a_ ) ,       ["""labels"""] )



					@require_flax
					def  lowercase__   (						self       :  Optional[int] ):
												self.assertEqual(find_labels(a_ ) ,       [] )
												self.assertEqual(find_labels(a_ ) ,       [] )
												self.assertEqual(find_labels(a_ ) ,       [] )





												class    __A(					UpperCAmelCase							):
																	pass
												self.assertEqual(find_labels(a_ ) ,       [] )










import numpy as np







def     UpperCAmelCase_		(					snake_case__    ,			snake_case__    ,			snake_case__ = 1E-12    ,			snake_case__ = 100    ,			)	->     tuple[float, np.ndarray]:



				"""simple docstring"""





				assert np.shape(snake_case__					)[0] == np.shape(snake_case__					)[1]
				# Ensure proper dimensionality.
				assert np.shape(snake_case__					)[0] == np.shape(snake_case__					)[0]
				# Ensure inputs are either both complex or both real
				assert np.iscomplexobj(snake_case__					) == np.iscomplexobj(snake_case__					)
				lowerCAmelCase__		  =  np.iscomplexobj(snake_case__					)
				if is_complex:
								# Ensure complex input_matrix is Hermitian
								assert np.array_equal(snake_case__    ,			input_matrix.conj().T					)

				# Set convergence to False. Will define convergence when we exceed max_iterations
				# or when we have small changes from one iteration to next.

				lowerCAmelCase__		  =  False
				lowerCAmelCase__		  =  0
				lowerCAmelCase__		  =  0
				lowerCAmelCase__		  =  1E12

				while not convergence:
								# Multiple matrix by the vector.
								lowerCAmelCase__		  =  np.dot(snake_case__    ,			snake_case__					)
								# Normalize the resulting output vector.
								lowerCAmelCase__		  =  w / np.linalg.norm(snake_case__					)
								# Find rayleigh quotient
								# (faster than usual b/c we know vector is normalized already)
								lowerCAmelCase__		  =  vector.conj().T if is_complex else vector.T
								lowerCAmelCase__		  =  np.dot(snake_case__    ,			np.dot(snake_case__    ,			snake_case__					)					)

								# Check convergence.
								lowerCAmelCase__		  =  np.abs(lambda_ - lambda_previous					) / lambda_
								iterations += 1

								if error <= error_tol or iterations >= max_iterations:
												lowerCAmelCase__		  =  True

								lowerCAmelCase__		  =  lambda_

				if is_complex:
								lowerCAmelCase__		  =  np.real(lambda_					)

				return lambda_, vector







def     UpperCAmelCase_		(					)	->     None:



				"""simple docstring"""





				lowerCAmelCase__		  =  np.array([[41, 4, 20], [4, 26, 30], [20, 30, 50]]					)
				lowerCAmelCase__		  =  np.array([41, 4, 20]					)
				lowerCAmelCase__		  =  real_input_matrix.astype(np.complexaaa					)
				lowerCAmelCase__		  =  np.triu(1j * complex_input_matrix    ,			1					)
				complex_input_matrix += imag_matrix
				complex_input_matrix += -1 * imag_matrix.T
				lowerCAmelCase__		  =  np.array([41, 4, 20]					).astype(np.complexaaa					)

				for problem_type in ["real", "complex"]:
								if problem_type == "real":
												lowerCAmelCase__		  =  real_input_matrix
												lowerCAmelCase__		  =  real_vector
								elif problem_type == "complex":
												lowerCAmelCase__		  =  complex_input_matrix
												lowerCAmelCase__		  =  complex_vector

								# Our implementation.
								lowerCAmelCase__  ,   lowerCAmelCase__		  =  power_iteration(snake_case__    ,			snake_case__					)

								# Numpy implementation.

								# Get eigenvalues and eigenvectors using built-in numpy
								# eigh (eigh used for symmetric or hermetian matrices).
								lowerCAmelCase__  ,   lowerCAmelCase__		  =  np.linalg.eigh(snake_case__					)
								# Last eigenvalue is the maximum one.
								lowerCAmelCase__		  =  eigen_values[-1]
								# Last column in this matrix is eigenvector corresponding to largest eigenvalue.
								lowerCAmelCase__		  =  eigen_vectors[:, -1]

								# Check our implementation and numpy gives close answers.
								assert np.abs(eigen_value - eigen_value_max					) <= 1E-6
								# Take absolute values element wise of each eigenvector.
								# as they are only unique to a minus sign.
								assert np.linalg.norm(np.abs(snake_case__					) - np.abs(snake_case__					)					) <= 1E-6


if __name__ == "__main__":
	import doctest

	doctest.testmod()
	test_power_iteration()
