


'''simple docstring'''







import inspect
import unittest

import numpy as np

from transformers import ViTConfig, is_flax_available
from transformers.testing_utils import require_flax, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor


if is_flax_available():
   import jax

   from transformers.models.vit.modeling_flax_vit import FlaxViTForImageClassification, FlaxViTModel


class 			__lowerCamelCase			(	unittest.TestCase	):
    """simple docstring"""


    def __init__(  self      :							Optional[int]				,							SCREAMING_SNAKE_CASE      :							Union[str, Any]				,							SCREAMING_SNAKE_CASE      :							Optional[int]=13				,							SCREAMING_SNAKE_CASE      :							List[Any]=30				,							SCREAMING_SNAKE_CASE      :							List[str]=2				,							SCREAMING_SNAKE_CASE      :							Any=3				,							SCREAMING_SNAKE_CASE      :							Union[str, Any]=True				,							SCREAMING_SNAKE_CASE      :							Dict=True				,							SCREAMING_SNAKE_CASE      :							Optional[Any]=32				,							SCREAMING_SNAKE_CASE      :							Tuple=5				,							SCREAMING_SNAKE_CASE      :							List[str]=4				,							SCREAMING_SNAKE_CASE      :							Optional[int]=37				,							SCREAMING_SNAKE_CASE      :							Dict="gelu"				,							SCREAMING_SNAKE_CASE      :							Optional[int]=0.1				,							SCREAMING_SNAKE_CASE      :							Dict=0.1				,							SCREAMING_SNAKE_CASE      :							List[Any]=10				,							SCREAMING_SNAKE_CASE      :							Any=0.02				,							):
           _A					:     Any     = parent
           _A					:     Optional[int]     = batch_size
           _A					:     List[str]     = image_size
           _A					:     Dict     = patch_size
           _A					:     List[Any]     = num_channels
           _A					:     Any     = is_training
           _A					:     str     = use_labels
           _A					:     int     = hidden_size
           _A					:     int     = num_hidden_layers
           _A					:     Any     = num_attention_heads
           _A					:     Optional[int]     = intermediate_size
           _A					:     Tuple     = hidden_act
           _A					:     Tuple     = hidden_dropout_prob
           _A					:     Union[str, Any]     = attention_probs_dropout_prob
           _A					:     Optional[Any]     = type_sequence_label_size
           _A					:     Union[str, Any]     = initializer_range

           # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
           _A					:     Union[str, Any]     = (image_size // patch_size) ** 2
           _A					:     Dict     = num_patches + 1


    def        A   (  self      :							List[Any]):
           _A					:     List[Any]     = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

           _A					:     Any     = ViTConfig(
               image_size=self.image_size				,							patch_size=self.patch_size				,							num_channels=self.num_channels				,							hidden_size=self.hidden_size				,							num_hidden_layers=self.num_hidden_layers				,							num_attention_heads=self.num_attention_heads				,							intermediate_size=self.intermediate_size				,							hidden_act=self.hidden_act				,							hidden_dropout_prob=self.hidden_dropout_prob				,							attention_probs_dropout_prob=self.attention_probs_dropout_prob				,							is_decoder=SCREAMING_SNAKE_CASE				,							initializer_range=self.initializer_range				,							)

           return config, pixel_values


    def        A   (  self      :							Optional[int]				,							SCREAMING_SNAKE_CASE      :							List[Any]				,							SCREAMING_SNAKE_CASE      :							Any):
           _A					:     List[str]     = FlaxViTModel(config=SCREAMING_SNAKE_CASE)
           _A					:     Any     = model(SCREAMING_SNAKE_CASE)
           # expected sequence length = num_patches + 1 (we add 1 for the [CLS] token)
           _A					:     Optional[int]     = (self.image_size, self.image_size)
           _A					:     str     = (self.patch_size, self.patch_size)
           _A					:     str     = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
           self.parent.assertEqual(result.last_hidden_state.shape				,							(self.batch_size, num_patches + 1, self.hidden_size))


    def        A   (  self      :							Union[str, Any]				,							SCREAMING_SNAKE_CASE      :							Optional[Any]				,							SCREAMING_SNAKE_CASE      :							List[str]):
           _A					:     Tuple     = self.type_sequence_label_size
           _A					:     Optional[int]     = FlaxViTForImageClassification(config=SCREAMING_SNAKE_CASE)
           _A					:     List[str]     = model(SCREAMING_SNAKE_CASE)
           self.parent.assertEqual(result.logits.shape				,							(self.batch_size, self.type_sequence_label_size))

           # test greyscale images
           _A					:     Dict     = 1
           _A					:     List[str]     = FlaxViTForImageClassification(SCREAMING_SNAKE_CASE)

           _A					:     Dict     = floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
           _A					:     Tuple     = model(SCREAMING_SNAKE_CASE)


    def        A   (  self      :							Tuple):
           _A					:     str     = self.prepare_config_and_inputs()
           (
               (
               _A
           )  ,			(
               _A
           )  ,			
           )					:     Dict     = config_and_inputs
           _A					:     List[Any]     = {'pixel_values': pixel_values}
           return config, inputs_dict




@require_flax
class 			__lowerCamelCase			(	a_    , unittest.TestCase	):
    """simple docstring"""
    a													=   (FlaxViTModel, FlaxViTForImageClassification) if is_flax_available() else ()


    def        A   (  self      :							List[str]):
           _A					:     List[Any]     = FlaxViTModelTester(self)
           _A					:     Optional[int]     = ConfigTester(self				,							config_class=SCREAMING_SNAKE_CASE				,							has_text_modality=SCREAMING_SNAKE_CASE				,							hidden_size=37)


    def        A   (  self      :							str):
           self.config_tester.run_common_tests()


    def        A   (  self      :							List[Any]):
           _A					:     Dict     = self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE)


    def        A   (  self      :							Optional[int]):
           _A					:     Any     = self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE)


    def        A   (  self      :							Optional[Any]):
           _A  ,			_A					:     int     = self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
                  _A					:     int     = model_class(SCREAMING_SNAKE_CASE)
                  _A					:     Any     = inspect.signature(model.__call__)
                  # signature.parameters is an OrderedDict => so arg_names order is deterministic
                  _A					:     List[Any]     = [*signature.parameters.keys()]

                  _A					:     List[Any]     = ['pixel_values']
                  self.assertListEqual(arg_names[:1]				,							SCREAMING_SNAKE_CASE)


    def        A   (  self      :							List[str]):
           _A  ,			_A					:     str     = self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
                  with self.subTest(model_class.__name__):
                         _A					:     Any     = self._prepare_for_class(SCREAMING_SNAKE_CASE				,							SCREAMING_SNAKE_CASE)
                         _A					:     Tuple     = model_class(SCREAMING_SNAKE_CASE)

                         @jax.jit
                         def model_jitted(SCREAMING_SNAKE_CASE      :							Optional[int]				,							**SCREAMING_SNAKE_CASE      :							str):
                                return model(pixel_values=SCREAMING_SNAKE_CASE				,							**SCREAMING_SNAKE_CASE)

                         with self.subTest('JIT Enabled'):
                                _A					:     Union[str, Any]     = model_jitted(**SCREAMING_SNAKE_CASE).to_tuple()

                         with self.subTest('JIT Disabled'):
                                with jax.disable_jit():
                                       _A					:     Dict     = model_jitted(**SCREAMING_SNAKE_CASE).to_tuple()

                         self.assertEqual(len(SCREAMING_SNAKE_CASE)				,							len(SCREAMING_SNAKE_CASE))
                         for jitted_output, output in zip(SCREAMING_SNAKE_CASE				,							SCREAMING_SNAKE_CASE):
                                self.assertEqual(jitted_output.shape				,							output.shape)


    @slow
    def        A   (  self      :							Optional[int]):
           for model_class_name in self.all_model_classes:
                  _A					:     Dict     = model_class_name.from_pretrained('google/vit-base-patch16-224')
                  _A					:     Optional[Any]     = model(np.ones((1, 3, 224, 224)))
                  self.assertIsNotNone(SCREAMING_SNAKE_CASE)










'''simple docstring'''







import string

import numpy






def 				lowerCAmelCase__	(    lowerCamelCase					:      int  ,lowerCamelCase					:      int       ):
       return b if a == 0 else greatest_common_divisor(b % a  ,lowerCamelCase       )


class 			__lowerCamelCase			:
    """simple docstring"""
    a													=   string.ascii_uppercase + string.digits
    # This cipher takes alphanumerics into account
    # i.e. a total of 36 characters

    # take x and return x % len(key_string)
    a													=   numpy.vectorize(lambda a_	: x % 36	)

    a													=   numpy.vectorize(a_	)


    def __init__(  self      :							List[Any]				,							SCREAMING_SNAKE_CASE      :							numpy.ndarray):
           _A					:     Union[str, Any]     = self.modulus(SCREAMING_SNAKE_CASE)  # mod36 calc's on the encrypt key
           self.check_determinant()  # validate the determinant of the encryption key
           _A					:     Optional[int]     = encrypt_key.shape[0]


    def        A   (  self      :							List[str]				,							SCREAMING_SNAKE_CASE      :							str):
           return self.key_string.index(SCREAMING_SNAKE_CASE)


    def        A   (  self      :							Union[str, Any]				,							SCREAMING_SNAKE_CASE      :							int):
           return self.key_string[round(SCREAMING_SNAKE_CASE)]


    def        A   (  self      :							List[Any]):
           _A					:     Optional[Any]     = round(numpy.linalg.det(self.encrypt_key))

           if det < 0:
                  _A					:     int     = det % len(self.key_string)

           _A					:     str     = len(self.key_string)
           if greatest_common_divisor(SCREAMING_SNAKE_CASE				,							len(self.key_string)) != 1:
                  _A					:     Optional[int]     = (
                      F'determinant modular {req_l} of encryption key({det}) '
                      F'is not co prime w.r.t {req_l}.\nTry another key.'
                  )
                  raise ValueError(SCREAMING_SNAKE_CASE)


    def        A   (  self      :							int				,							SCREAMING_SNAKE_CASE      :							str):
           _A					:     List[Any]     = [char for char in text.upper() if char in self.key_string]

           _A					:     List[str]     = chars[-1]
           while len(SCREAMING_SNAKE_CASE) % self.break_key != 0:
                  chars.append(SCREAMING_SNAKE_CASE)

           return "".join(SCREAMING_SNAKE_CASE)


    def        A   (  self      :							Optional[int]				,							SCREAMING_SNAKE_CASE      :							str):
           _A					:     Optional[int]     = self.process_text(text.upper())
           _A					:     List[str]     = ''

           for i in range(0				,							len(SCREAMING_SNAKE_CASE) - self.break_key + 1				,							self.break_key):
                  _A					:     Optional[Any]     = text[i : i + self.break_key]
                  _A					:     Optional[int]     = [self.replace_letters(SCREAMING_SNAKE_CASE) for char in batch]
                  _A					:     Tuple     = numpy.array([vec]).T
                  _A					:     List[str]     = self.modulus(self.encrypt_key.dot(SCREAMING_SNAKE_CASE)).T.tolist()[
                      0
                  ]
                  _A					:     str     = ''.join(
                      self.replace_digits(SCREAMING_SNAKE_CASE) for num in batch_encrypted)
                  encrypted += encrypted_batch

           return encrypted


    def        A   (  self      :							Union[str, Any]):
           _A					:     List[Any]     = round(numpy.linalg.det(self.encrypt_key))

           if det < 0:
                  _A					:     Optional[int]     = det % len(self.key_string)
           _A					:     List[str]     = None
           for i in range(len(self.key_string)):
                  if (det * i) % len(self.key_string) == 1:
                         _A					:     Union[str, Any]     = i
                         break

           _A					:     Dict     = (
               det_inv
               * numpy.linalg.det(self.encrypt_key)
               * numpy.linalg.inv(self.encrypt_key)
           )

           return self.to_int(self.modulus(SCREAMING_SNAKE_CASE))


    def        A   (  self      :							Any				,							SCREAMING_SNAKE_CASE      :							str):
           _A					:     List[str]     = self.make_decrypt_key()
           _A					:     Dict     = self.process_text(text.upper())
           _A					:     str     = ''

           for i in range(0				,							len(SCREAMING_SNAKE_CASE) - self.break_key + 1				,							self.break_key):
                  _A					:     Optional[int]     = text[i : i + self.break_key]
                  _A					:     Union[str, Any]     = [self.replace_letters(SCREAMING_SNAKE_CASE) for char in batch]
                  _A					:     Tuple     = numpy.array([vec]).T
                  _A					:     Optional[int]     = self.modulus(decrypt_key.dot(SCREAMING_SNAKE_CASE)).T.tolist()[0]
                  _A					:     Tuple     = ''.join(
                      self.replace_digits(SCREAMING_SNAKE_CASE) for num in batch_decrypted)
                  decrypted += decrypted_batch

           return decrypted






def 				lowerCAmelCase__	(    ):
       _A					:     List[Any]     = int(input('Enter the order of the encryption key: '       )       )
       _A					:     List[str]     = []

       print('Enter each row of the encryption key with space separated integers'       )
       for _ in range(lowerCamelCase       ):
              _A					:     str     = [int(lowerCamelCase       ) for x in input().split()]
              hill_matrix.append(lowerCamelCase       )

       _A					:     Dict     = HillCipher(numpy.array(lowerCamelCase       )       )

       print('Would you like to encrypt or decrypt some text? (1 or 2)'       )
       _A					:     List[str]     = input('\n1. Encrypt\n2. Decrypt\n'       )
       if option == "1":
              _A					:     int     = input('What text would you like to encrypt?: '       )
              print('Your encrypted text is:'       )
              print(hc.encrypt(lowerCamelCase       )       )
       elif option == "2":
              _A					:     int     = input('What text would you like to decrypt?: '       )
              print('Your decrypted text is:'       )
              print(hc.decrypt(lowerCamelCase       )       )


if __name__ == "__main__":
   import doctest

   doctest.testmod()

   main()






