


import string

import numpy



def        UpperCamelCase_(   lowerCamelCase_							,				lowerCamelCase_				)					->		int:
    return b if a == 0 else greatest_common_divisor(b % a							,				lowerCamelCase_				)






class _lowerCamelCase:
       lowercase_				:			Tuple									=    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)
       lowercase_				:			List[Any]									=    numpy.vectorize(lambda _a     : x % 36     )

       lowercase_				:			Union[str, Any]									=    numpy.vectorize(_a     )
       def __init__(      self,   lowerCamelCase) ->     None:




           """simple docstring"""

           _lowercase :							str   	=	self.modulus(lowerCamelCase)  # mod36 calc's on the encrypt key
           self.check_determinant()  # validate the determinant of the encryption key
           _lowercase :							str   	=	encrypt_key.shape[0]
       def     UpperCamelCase  (      self,   lowerCamelCase) ->     int:




           """simple docstring"""

           return self.key_string.index(lowerCamelCase)
       def     UpperCamelCase  (      self,   lowerCamelCase) ->     str:




           """simple docstring"""

           return self.key_string[round(lowerCamelCase)]
       def     UpperCamelCase  (      self) ->     None:




           """simple docstring"""

           _lowercase :							Optional[Any]   	=	round(numpy.linalg.det(self.encrypt_key))

           if det < 0:
               _lowercase :							Tuple   	=	det % len(self.key_string)

           _lowercase :							Optional[Any]   	=	len(self.key_string)
           if greatest_common_divisor(lowerCamelCase,   len(self.key_string)) != 1:
               _lowercase :							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(lowerCamelCase)
       def     UpperCamelCase  (      self,   lowerCamelCase) ->     str:




           """simple docstring"""

           _lowercase :							Union[str, Any]   	=	[char for char in text.upper() if char in self.key_string]

           _lowercase :							Optional[Any]   	=	chars[-1]
           while len(lowerCamelCase) % self.break_key != 0:
               chars.append(lowerCamelCase)

           return "".join(lowerCamelCase)
       def     UpperCamelCase  (      self,   lowerCamelCase) ->     str:




           """simple docstring"""

           _lowercase :							str   	=	self.process_text(text.upper())
           _lowercase :							List[Any]   	=	''

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

           return encrypted
       def     UpperCamelCase  (      self) ->     numpy.ndarray:




           """simple docstring"""

           _lowercase :							Any   	=	round(numpy.linalg.det(self.encrypt_key))

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

           _lowercase :							Tuple   	=	(
               det_inv
               * numpy.linalg.det(self.encrypt_key)
               * numpy.linalg.inv(self.encrypt_key)
           )

           return self.to_int(self.modulus(lowerCamelCase))




       def     UpperCamelCase  (      self,   lowerCamelCase) ->     str:




           """simple docstring"""

           _lowercase :							Tuple   	=	self.make_decrypt_key()
           _lowercase :							Optional[Any]   	=	self.process_text(text.upper())
           _lowercase :							str   	=	''

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

           return decrypted



def        UpperCamelCase_(   )					->		None:
    _lowercase :							Tuple   	=	int(input('Enter the order of the encryption key: '				)				)
    _lowercase :							List[str]   	=	[]

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

    _lowercase :							List[str]   	=	HillCipher(numpy.array(lowerCamelCase_				)				)

    print('Would you like to encrypt or decrypt some text? (1 or 2)'				)
    _lowercase :							Dict   	=	input('\n1. Encrypt\n2. Decrypt\n'				)
    if option == "1":
        _lowercase :							str   	=	input('What text would you like to encrypt?: '				)
        print('Your encrypted text is:'				)
        print(hc.encrypt(lowerCamelCase_				)				)
    elif option == "2":
        _lowercase :							Optional[Any]   	=	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()






import subprocess
import sys

from transformers import BertConfig, BertModel, BertTokenizer, pipeline
from transformers.testing_utils import TestCasePlus, require_torch






class _lowerCamelCase(		_a     ):
       @require_torch
       def     UpperCamelCase  (      self) ->     int:




           """simple docstring"""

           _lowercase :							Optional[Any]   	=	'\nfrom transformers import BertConfig, BertModel, BertTokenizer, pipeline\n        '

           _lowercase :							Union[str, Any]   	=	'\nmname = "hf-internal-testing/tiny-random-bert"\nBertConfig.from_pretrained(mname)\nBertModel.from_pretrained(mname)\nBertTokenizer.from_pretrained(mname)\npipe = pipeline(task="fill-mask", model=mname)\nprint("success")\n        '

           _lowercase :							List[str]   	=	'\nimport socket\ndef offline_socket(*args, **kwargs): raise RuntimeError("Offline mode is enabled, we shouldn\'t access internet")\nsocket.socket = offline_socket\n        '

           # Force fetching the files so that we can use the cache
           _lowercase :							Union[str, Any]   	=	'hf-internal-testing/tiny-random-bert'
           BertConfig.from_pretrained(lowerCamelCase)
           BertModel.from_pretrained(lowerCamelCase)
           BertTokenizer.from_pretrained(lowerCamelCase)
           pipeline(task='fill-mask',   model=lowerCamelCase)

           # baseline - just load from_pretrained with normal network
           _lowercase :							Any   	=	[sys.executable, '-c', '\n'.join([load, run, mock])]

           # should succeed
           _lowercase :							List[str]   	=	self.get_env()
           # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files
           _lowercase :							Any   	=	'1'
           _lowercase :							List[Any]   	=	subprocess.run(lowerCamelCase,   env=lowerCamelCase,   check=lowerCamelCase,   capture_output=lowerCamelCase)
           self.assertEqual(result.returncode,   0,   result.stderr)
           self.assertIn('success',   result.stdout.decode())
       @require_torch
       def     UpperCamelCase  (      self) ->     List[Any]:




           """simple docstring"""

           _lowercase :							int   	=	'\nfrom transformers import BertConfig, BertModel, BertTokenizer, pipeline\n        '

           _lowercase :							Union[str, Any]   	=	'\nmname = "hf-internal-testing/tiny-random-bert"\nBertConfig.from_pretrained(mname)\nBertModel.from_pretrained(mname)\nBertTokenizer.from_pretrained(mname)\npipe = pipeline(task="fill-mask", model=mname)\nprint("success")\n        '

           _lowercase :							List[Any]   	=	'\nimport socket\ndef offline_socket(*args, **kwargs): raise socket.error("Faking flaky internet")\nsocket.socket = offline_socket\n        '

           # Force fetching the files so that we can use the cache
           _lowercase :							Any   	=	'hf-internal-testing/tiny-random-bert'
           BertConfig.from_pretrained(lowerCamelCase)
           BertModel.from_pretrained(lowerCamelCase)
           BertTokenizer.from_pretrained(lowerCamelCase)
           pipeline(task='fill-mask',   model=lowerCamelCase)

           # baseline - just load from_pretrained with normal network
           _lowercase :							List[str]   	=	[sys.executable, '-c', '\n'.join([load, run, mock])]

           # should succeed
           _lowercase :							Any   	=	self.get_env()
           _lowercase :							str   	=	subprocess.run(lowerCamelCase,   env=lowerCamelCase,   check=lowerCamelCase,   capture_output=lowerCamelCase)
           self.assertEqual(result.returncode,   0,   result.stderr)
           self.assertIn('success',   result.stdout.decode())
       @require_torch
       def     UpperCamelCase  (      self) ->     Union[str, Any]:




           """simple docstring"""

           _lowercase :							Tuple   	=	'\nfrom transformers import BertConfig, BertModel, BertTokenizer\n        '

           _lowercase :							int   	=	'\nmname = "hf-internal-testing/tiny-random-bert-sharded"\nBertConfig.from_pretrained(mname)\nBertModel.from_pretrained(mname)\nprint("success")\n        '

           _lowercase :							List[Any]   	=	'\nimport socket\ndef offline_socket(*args, **kwargs): raise ValueError("Offline mode is enabled")\nsocket.socket = offline_socket\n        '

           # baseline - just load from_pretrained with normal network
           _lowercase :							int   	=	[sys.executable, '-c', '\n'.join([load, run])]

           # should succeed
           _lowercase :							List[str]   	=	self.get_env()
           _lowercase :							Dict   	=	subprocess.run(lowerCamelCase,   env=lowerCamelCase,   check=lowerCamelCase,   capture_output=lowerCamelCase)
           self.assertEqual(result.returncode,   0,   result.stderr)
           self.assertIn('success',   result.stdout.decode())

           # next emulate no network
           _lowercase :							Union[str, Any]   	=	[sys.executable, '-c', '\n'.join([load, mock, run])]

           # Doesn't fail anymore since the model is in the cache due to other tests, so commenting this.
           # env["TRANSFORMERS_OFFLINE"] = "0"
           # result = subprocess.run(cmd, env=env, check=False, capture_output=True)
           # self.assertEqual(result.returncode, 1, result.stderr)

           # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files
           _lowercase :							Optional[Any]   	=	'1'
           _lowercase :							Optional[Any]   	=	subprocess.run(lowerCamelCase,   env=lowerCamelCase,   check=lowerCamelCase,   capture_output=lowerCamelCase)
           self.assertEqual(result.returncode,   0,   result.stderr)
           self.assertIn('success',   result.stdout.decode())
       @require_torch
       def     UpperCamelCase  (      self) ->     Optional[Any]:




           """simple docstring"""

           _lowercase :							Optional[Any]   	=	'\nfrom transformers import pipeline\n        '
           _lowercase :							Dict   	=	'\nmname = "hf-internal-testing/tiny-random-bert"\npipe = pipeline(model=mname)\n        '

           _lowercase :							Optional[Any]   	=	'\nimport socket\ndef offline_socket(*args, **kwargs): raise socket.error("Offline mode is enabled")\nsocket.socket = offline_socket\n        '
           _lowercase :							Tuple   	=	self.get_env()
           _lowercase :							Tuple   	=	'1'
           _lowercase :							Union[str, Any]   	=	[sys.executable, '-c', '\n'.join([load, mock, run])]
           _lowercase :							Tuple   	=	subprocess.run(lowerCamelCase,   env=lowerCamelCase,   check=lowerCamelCase,   capture_output=lowerCamelCase)
           self.assertEqual(result.returncode,   1,   result.stderr)
           self.assertIn(
               'You cannot infer task automatically within `pipeline` when using offline mode',   result.stderr.decode().replace('\n',   ''),   )




       @require_torch
       def     UpperCamelCase  (      self) ->     Tuple:




           """simple docstring"""

           _lowercase :							Dict   	=	'\nfrom transformers import AutoModel\n        '
           _lowercase :							int   	=	'\nmname = "hf-internal-testing/test_dynamic_model"\nAutoModel.from_pretrained(mname, trust_remote_code=True)\nprint("success")\n        '

           # baseline - just load from_pretrained with normal network
           _lowercase :							Optional[int]   	=	[sys.executable, '-c', '\n'.join([load, run])]

           # should succeed
           _lowercase :							int   	=	self.get_env()
           _lowercase :							List[str]   	=	subprocess.run(lowerCamelCase,   env=lowerCamelCase,   check=lowerCamelCase,   capture_output=lowerCamelCase)
           self.assertEqual(result.returncode,   0,   result.stderr)
           self.assertIn('success',   result.stdout.decode())

           # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files
           _lowercase :							Tuple   	=	'1'
           _lowercase :							Dict   	=	subprocess.run(lowerCamelCase,   env=lowerCamelCase,   check=lowerCamelCase,   capture_output=lowerCamelCase)
           self.assertEqual(result.returncode,   0,   result.stderr)
           self.assertIn('success',   result.stdout.decode())


