



'''simple docstring'''





import bza
import gzip
import lzma
import os
import shutil
import struct
import tarfile
import warnings
import zipfile
from abc import ABC, abstractmethod
from pathlib import Path
from typing import Dict, List, Optional, Type, Union

from .. import config
from .filelock import FileLock
from .logging import get_logger


lowercase_									=    get_logger(__name__)






class __A     :



 '''simple docstring'''







 def __init__(self					,  A = None			)       ->	int:


      """simple docstring"""



      _a           =    (
          os.path.join(A					,  config.EXTRACTED_DATASETS_DIR			) if cache_dir else config.EXTRACTED_DATASETS_PATH
      )
      _a           =    Extractor



 def    a__    (self					,  A			)       ->	str:


      """simple docstring"""



      from .file_utils import hash_url_to_filename

      # Path where we extract compressed archives
      # We extract in the cache dir, and get the extracted path name by hashing the original path"
      _a           =    os.path.abspath(A			)
      return os.path.join(self.extract_dir					,  hash_url_to_filename(A			)			)



 def    a__    (self					,  A					,  A			)       ->	bool:


      """simple docstring"""



      return force_extract or (
          not os.path.isfile(A			) and not (os.path.isdir(A			) and os.listdir(A			))
      )



 def    a__    (self					,  A					,  A = False			)       ->	str:


      """simple docstring"""



      _a           =    self.extractor.infer_extractor_format(A			)
      if not extractor_format:
           return input_path
      _a           =    self._get_output_path(A			)
      if self._do_extract(A					,  A			):
           self.extractor.extract(A					,  A					,  A			)
      return output_path






class __A     (    A		):



 '''simple docstring'''







 @classmethod
 @abstractmethod
 def    a__    (cls					,  A					,  **A			)       ->	bool:


      """simple docstring"""



      ...



 @staticmethod
 @abstractmethod
 def    a__    (A					,  A			)       ->	None:


      """simple docstring"""



      ...






class __A     (    A  ,  A		):



 '''simple docstring'''







 __lowerCamelCase       :			List[bytes]		=			[]



 @staticmethod
 def    a__    (A					,  A			)       ->	int:


      """simple docstring"""



      with open(A					,  '''rb'''			) as f:
           return f.read(A			)



 @classmethod
 def    a__    (cls					,  A					,  A = b""			)       ->	bool:


      """simple docstring"""



      if not magic_number:
           _a           =    max(len(A			) for cls_magic_number in cls.magic_numbers			)
           try:
                _a           =    cls.read_magic_number(A					,  A			)
           except OSError:
                return False
      return any(magic_number.startswith(A			) for cls_magic_number in cls.magic_numbers			)






class __A     (    A		):



 '''simple docstring'''







 @classmethod
 def    a__    (cls					,  A					,  **A			)       ->	bool:


      """simple docstring"""



      return tarfile.is_tarfile(A			)



 @staticmethod
 def    a__    (A					,  A			)       ->	List[Any]:


      """simple docstring"""



      def resolved(A			) -> str:
           return os.path.realpath(os.path.abspath(A			)			)

      def badpath(A					,  A			) -> bool:
           # joinpath will ignore base if path is absolute
           return not resolved(os.path.join(A					,  A			)			).startswith(A			)

      def badlink(A					,  A			) -> bool:
           # Links are interpreted relative to the directory containing the link
           _a           =    resolved(os.path.join(A					,  os.path.dirname(info.name			)			)			)
           return badpath(info.linkname					,  base=A			)

      _a           =    resolved(A			)

      for finfo in members:
           if badpath(finfo.name					,  A			):
                logger.error(f'''Extraction of {finfo.name} is blocked (illegal path)'''			)
           elif finfo.issym() and badlink(A					,  A			):
                logger.error(f'''Extraction of {finfo.name} is blocked: Symlink to {finfo.linkname}'''			)
           elif finfo.islnk() and badlink(A					,  A			):
                logger.error(f'''Extraction of {finfo.name} is blocked: Hard link to {finfo.linkname}'''			)
           else:
                yield finfo



 @staticmethod
 def    a__    (A					,  A			)       ->	None:


      """simple docstring"""



      os.makedirs(A					,  exist_ok=A			)
      _a           =    tarfile.open(A			)
      tar_file.extractall(A					,  members=TarExtractor.safemembers(A					,  A			)			)
      tar_file.close()






class __A     (    A		):



 '''simple docstring'''







 __lowerCamelCase       :			int		=			[b'\x1F\x8B']



 @staticmethod
 def    a__    (A					,  A			)       ->	None:


      """simple docstring"""



      with gzip.open(A					,  '''rb'''			) as gzip_file:
           with open(A					,  '''wb'''			) as extracted_file:
                shutil.copyfileobj(A					,  A			)






class __A     (    A		):



 '''simple docstring'''







 __lowerCamelCase       :			Union[str, Any]		=			[
     b'PK\x03\x04',
     b'PK\x05\x06',  # empty archive
     b'PK\x07\x08',  # spanned archive
 ]



 @classmethod
 def    a__    (cls					,  A					,  A = b""			)       ->	bool:


      """simple docstring"""



      if super().is_extractable(A					,  magic_number=A			):
           return True
      try:
           # Alternative version of zipfile.is_zipfile that has less false positives, but misses executable zip archives.
           # From: https://github.com/python/cpython/pull/5053
           from zipfile import (
               _CD_SIGNATURE,
               _ECD_DISK_NUMBER,
               _ECD_DISK_START,
               _ECD_ENTRIES_TOTAL,
               _ECD_OFFSET,
               _ECD_SIZE,
               _EndRecData,
               sizeCentralDir,
               stringCentralDir,
               structCentralDir,
           )

           with open(A					,  '''rb'''			) as fp:
                _a           =    _EndRecData(A			)
                if endrec:
                     if endrec[_ECD_ENTRIES_TOTAL] == 0 and endrec[_ECD_SIZE] == 0 and endrec[_ECD_OFFSET] == 0:
                          return True  # Empty zipfiles are still zipfiles
                     elif endrec[_ECD_DISK_NUMBER] == endrec[_ECD_DISK_START]:
                          fp.seek(endrec[_ECD_OFFSET]			)  # Central directory is on the same disk
                          if fp.tell() == endrec[_ECD_OFFSET] and endrec[_ECD_SIZE] >= sizeCentralDir:
                               _a           =    fp.read(A			)  # CD is where we expect it to be
                               if len(A			) == sizeCentralDir:
                                    _a           =    struct.unpack(A					,  A			)  # CD is the right size
                                    if centdir[_CD_SIGNATURE] == stringCentralDir:
                                         return True  # First central directory entry  has correct magic number
           return False
      except Exception:  # catch all errors in case future python versions change the zipfile internals
           return False



 @staticmethod
 def    a__    (A					,  A			)       ->	None:


      """simple docstring"""



      os.makedirs(A					,  exist_ok=A			)
      with zipfile.ZipFile(A					,  '''r'''			) as zip_file:
           zip_file.extractall(A			)
           zip_file.close()






class __A     (    A		):



 '''simple docstring'''







 __lowerCamelCase       :			str		=			[b'\xFD\x37\x7A\x58\x5A\x00']



 @staticmethod
 def    a__    (A					,  A			)       ->	None:


      """simple docstring"""



      with lzma.open(A			) as compressed_file:
           with open(A					,  '''wb'''			) as extracted_file:
                shutil.copyfileobj(A					,  A			)






class __A     (    A		):



 '''simple docstring'''







 __lowerCamelCase       :			Any		=			[b'Rar!\x1a\x07\x00', b'Rar!\x1a\x07\x01\x00']  # RAR_ID  # RAR5_ID



 @staticmethod
 def    a__    (A					,  A			)       ->	None:


      """simple docstring"""



      if not config.RARFILE_AVAILABLE:
           raise ImportError('''Please pip install rarfile'''			)
      import rarfile

      os.makedirs(A					,  exist_ok=A			)
      _a           =    rarfile.RarFile(A			)
      rf.extractall(A			)
      rf.close()






class __A     (    A		):



 '''simple docstring'''







 __lowerCamelCase       :			Any		=			[b'\x28\xb5\x2F\xFD']



 @staticmethod
 def    a__    (A					,  A			)       ->	None:


      """simple docstring"""



      if not config.ZSTANDARD_AVAILABLE:
           raise ImportError('''Please pip install zstandard'''			)
      import zstandard as zstd

      _a           =    zstd.ZstdDecompressor()
      with open(A					,  '''rb'''			) as ifh, open(A					,  '''wb'''			) as ofh:
           dctx.copy_stream(A					,  A			)






class __A     (    A		):



 '''simple docstring'''







 __lowerCamelCase       :			List[str]		=			[b'\x42\x5A\x68']



 @staticmethod
 def    a__    (A					,  A			)       ->	None:


      """simple docstring"""



      with bza.open(A					,  '''rb'''			) as compressed_file:
           with open(A					,  '''wb'''			) as extracted_file:
                shutil.copyfileobj(A					,  A			)






class __A     (    A		):



 '''simple docstring'''







 __lowerCamelCase       :			Tuple		=			[b'\x37\x7A\xBC\xAF\x27\x1C']



 @staticmethod
 def    a__    (A					,  A			)       ->	None:


      """simple docstring"""



      if not config.PY7ZR_AVAILABLE:
           raise ImportError('''Please pip install py7zr'''			)
      import pyazr

      os.makedirs(A					,  exist_ok=A			)
      with pyazr.SevenZipFile(A					,  '''r'''			) as archive:
           archive.extractall(A			)






class __A     (    A		):



 '''simple docstring'''







 __lowerCamelCase       :			Optional[int]		=			[b'\x04\x22\x4D\x18']



 @staticmethod
 def    a__    (A					,  A			)       ->	None:


      """simple docstring"""



      if not config.LZ4_AVAILABLE:
           raise ImportError('''Please pip install lz4'''			)
      import lza.frame

      with lza.frame.open(A					,  '''rb'''			) as compressed_file:
           with open(A					,  '''wb'''			) as extracted_file:
                shutil.copyfileobj(A					,  A			)






class __A     :



 '''simple docstring'''







 __lowerCamelCase       :			Dict[str, Type[BaseExtractor]]		=			{
     "tar": TarExtractor,
     "gzip": GzipExtractor,
     "zip": ZipExtractor,
     "xz": XzExtractor,
     "rar": RarExtractor,
     "zstd": ZstdExtractor,
     "bz2": BzipaExtractor,
     "7z": SevenZipExtractor,  # <Added version="2.4.0"/>
     "lz4": LzaExtractor,  # <Added version="2.4.0"/>
 }



 @classmethod
 def    a__    (cls			)       ->	Tuple:


      """simple docstring"""



      return max(
          len(A			)
          for extractor in cls.extractors.values()
          if issubclass(A					,  A			)
          for extractor_magic_number in extractor.magic_numbers			)



 @staticmethod
 def    a__    (A					,  A			)       ->	Tuple:


      """simple docstring"""



      try:
           return MagicNumberBaseExtractor.read_magic_number(A					,  magic_number_length=A			)
      except OSError:
           return b""



 @classmethod
 def    a__    (cls					,  A					,  A = False			)       ->	bool:


      """simple docstring"""



      warnings.warn(
          '''Method \'is_extractable\' was deprecated in version 2.4.0 and will be removed in 3.0.0. '''
          '''Use \'infer_extractor_format\' instead.'''					,  category=A					,  )
      _a           =    cls.infer_extractor_format(A			)
      if extractor_format:
           return True if not return_extractor else (True, cls.extractors[extractor_format])
      return False if not return_extractor else (False, None)



 @classmethod
 def    a__    (cls					,  A			)       ->	str:  # <Added version="2.4.0"/>


      """simple docstring"""



      _a           =    cls._get_magic_number_max_length()
      _a           =    cls._read_magic_number(A					,  A			)
      for extractor_format, extractor in cls.extractors.items():
           if extractor.is_extractable(A					,  magic_number=A			):
                return extractor_format



 @classmethod
 def    a__    (cls					,  A					,  A					,  A = None					,  A = "deprecated"					,  )       ->	None:


      """simple docstring"""



      os.makedirs(os.path.dirname(A			)					,  exist_ok=A			)
      # Prevent parallel extractions
      _a           =    str(Path(A			).with_suffix('''.lock'''			)			)
      with FileLock(A			):
           shutil.rmtree(A					,  ignore_errors=A			)
           if extractor_format or extractor != "deprecated":
                if extractor != "deprecated" or not isinstance(A					,  A			):  # passed as positional arg
                     warnings.warn(
                         '''Parameter \'extractor\' was deprecated in version 2.4.0 and will be removed in 3.0.0. '''
                         '''Use \'extractor_format\' instead.'''					,  category=A					,  )
                     _a           =    extractor if extractor != '''deprecated''' else extractor_format
                else:
                     _a           =    cls.extractors[extractor_format]
                return extractor.extract(A					,  A			)
           else:
                warnings.warn(
                    '''Parameter \'extractor_format\' was made required in version 2.4.0 and not passing it will raise an '''
                    '''exception in 3.0.0.'''					,  category=A					,  )
                for extractor in cls.extractors.values():
                     if extractor.is_extractable(A			):
                          return extractor.extract(A					,  A			)








'''simple docstring'''





def lowerCAmelCase    (__A):



     """simple docstring"""



     return credit_card_number.startswith(('''34''', '''35''', '''37''', '''4''', '''5''', '''6'''))




def lowerCAmelCase    (__A):



     """simple docstring"""



     _a           =    credit_card_number
     _a           =    0
     _a           =    len(__A) - 2
     for i in range(__A    ,      -1    ,      -2):
          #  double the value of every second digit
          _a           =    int(cc_number[i])
          digit *= 2
          # If doubling of a number results in a two digit number
          # i.e greater than 9(e.g., 6 × 2 = 12),
          # then add the digits of the product (e.g., 12: 1 + 2 = 3, 15: 1 + 5 = 6),
          # to get a single digit number.
          if digit > 9:
               digit %= 10
               digit += 1
          _a           =    cc_number[:i] + str(__A) + cc_number[i + 1 :]
          total += digit

     # Sum up the remaining digits
     for i in range(len(__A) - 1    ,      -1    ,      -2):
          total += int(cc_number[i])

     return total % 10 == 0




def lowerCAmelCase    (__A):



     """simple docstring"""



     _a           =    F'''{credit_card_number} is an invalid credit card number because'''
     if not credit_card_number.isdigit():
          print(F'''{error_message} it has nonnumerical characters.''')
          return False

     if not 13 <= len(__A) <= 16:
          print(F'''{error_message} of its length.''')
          return False

     if not validate_initial_digits(__A):
          print(F'''{error_message} of its first two digits.''')
          return False

     if not luhn_validation(__A):
          print(F'''{error_message} it fails the Luhn check.''')
          return False

     print(F'''{credit_card_number} is a valid credit card number.''')
     return True


if __name__ == "__main__":
  import doctest

  doctest.testmod()
  validate_credit_card_number("4111111111111111")
  validate_credit_card_number("32323")



