'''simple docstring'''







import os
import textwrap

import pyarrow as pa
import pytest

from datasets import ClassLabel, Features, Image
from datasets.packaged_modules.csv.csv import Csv

from ..utils import require_pil






@pytest.fixture
def 				lowerCAmelCase__	(    lowerCamelCase					:      Union[str, Any]       ):
       _A					:     List[Any]     = tmp_path / 'file.csv'
       _A					:     Dict     = textwrap.dedent(
           '\\n        header1,header2\n        1,2\n        10,20\n        '       )
       with open(lowerCamelCase  ,'w'       ) as f:
              f.write(lowerCamelCase       )
       return str(lowerCamelCase       )






@pytest.fixture
def 				lowerCAmelCase__	(    lowerCamelCase					:      Dict       ):
       _A					:     List[Any]     = tmp_path / 'malformed_file.csv'
       _A					:     Union[str, Any]     = textwrap.dedent(
           '\\n        header1,header2\n        1,2\n        10,20,\n        '       )
       with open(lowerCamelCase  ,'w'       ) as f:
              f.write(lowerCamelCase       )
       return str(lowerCamelCase       )






@pytest.fixture
def 				lowerCAmelCase__	(    lowerCamelCase					:      Any  ,lowerCamelCase					:      str       ):
       _A					:     Dict     = tmp_path / 'csv_with_image.csv'
       _A					:     int     = textwrap.dedent(
           F'\\n        image\n        {image_file}\n        '       )
       with open(lowerCamelCase  ,'w'       ) as f:
              f.write(lowerCamelCase       )
       return str(lowerCamelCase       )






@pytest.fixture
def 				lowerCAmelCase__	(    lowerCamelCase					:      Union[str, Any]       ):
       _A					:     str     = tmp_path / 'csv_with_label.csv'
       _A					:     Any     = textwrap.dedent(
           '\\n        label\n        good\n        bad\n        good\n        '       )
       with open(lowerCamelCase  ,'w'       ) as f:
              f.write(lowerCamelCase       )
       return str(lowerCamelCase       )






@pytest.fixture
def 				lowerCAmelCase__	(    lowerCamelCase					:      int       ):
       _A					:     List[Any]     = tmp_path / 'csv_with_int_list.csv'
       _A					:     Optional[int]     = textwrap.dedent(
           '\\n        int_list\n        1 2 3\n        4 5 6\n        7 8 9\n        '       )
       with open(lowerCamelCase  ,'w'       ) as f:
              f.write(lowerCamelCase       )
       return str(lowerCamelCase       )






def 				lowerCAmelCase__	(    lowerCamelCase					:      Any  ,lowerCamelCase					:      int  ,lowerCamelCase					:      Optional[Any]       ):
       _A					:     Dict     = Csv()
       _A					:     str     = csv._generate_tables([[csv_file, malformed_csv_file]]       )
       with pytest.raises(lowerCamelCase  ,match='Error tokenizing data'       ):
              for _ in generator:
                     pass
       assert any(
           record.levelname == 'ERROR'
           and 'Failed to read file' in record.message
           and os.path.basename(lowerCamelCase       ) in record.message
           for record in caplog.records       )






@require_pil
def 				lowerCAmelCase__	(    lowerCamelCase					:      str       ):
       with open(lowerCamelCase  ,encoding='utf-8'       ) as f:
              _A					:     int     = f.read().splitlines()[1]
       _A					:     Union[str, Any]     = Csv(encoding='utf-8'  ,features=Features({'image': Image()}       )       )
       _A					:     Optional[Any]     = csv._generate_tables([[csv_file_with_image]]       )
       _A					:     Tuple     = pa.concat_tables([table for _, table in generator]       )
       assert pa_table.schema.field('image'       ).type == Image()()
       _A					:     Optional[int]     = pa_table.to_pydict()['image']
       assert generated_content == [{"path": image_file, "bytes": None}]






def 				lowerCAmelCase__	(    lowerCamelCase					:      Optional[Any]       ):
       with open(lowerCamelCase  ,encoding='utf-8'       ) as f:
              _A					:     Optional[Any]     = f.read().splitlines()[1:]
       _A					:     Dict     = Csv(encoding='utf-8'  ,features=Features({'label': ClassLabel(names=['good', 'bad']       )}       )       )
       _A					:     Optional[Any]     = csv._generate_tables([[csv_file_with_label]]       )
       _A					:     Optional[Any]     = pa.concat_tables([table for _, table in generator]       )
       assert pa_table.schema.field('label'       ).type == ClassLabel(names=['good', 'bad']       )()
       _A					:     Any     = pa_table.to_pydict()['label']
       assert generated_content == [ClassLabel(names=['good', 'bad']       ).straint(lowerCamelCase       ) for label in labels]






def 				lowerCAmelCase__	(    lowerCamelCase					:      List[str]       ):
       _A					:     Tuple     = Csv(encoding='utf-8'  ,sep=','  ,converters={'int_list': lambda lowerCamelCase       : [int(lowerCamelCase       ) for i in x.split()]}       )
       _A					:     Tuple     = csv._generate_tables([[csv_file_with_int_list]]       )
       _A					:     Dict     = pa.concat_tables([table for _, table in generator]       )
       assert pa.types.is_list(pa_table.schema.field('int_list'       ).type       )
       _A					:     Optional[int]     = pa_table.to_pydict()['int_list']
       assert generated_content == [[1, 2, 3], [4, 5, 6], [7, 8, 9]]










'''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()






