





import asyncio
import os
import re
import sys
import tempfile
import unittest
from contextlib import contextmanager
from copy import deepcopy
from distutils.util import strtobool
from enum import Enum
from importlib.util import find_spec
from pathlib import Path
from unittest.mock import patch

import pyarrow as pa
import pytest
import requests
from packaging import version

from datasets import config


if config.PY_VERSION < version.parse('3.8'):
       import importlib_metadata
else:
       import importlib.metadata as importlib_metadata



def 	_a						(   UpperCAmelCase      ,  UpperCAmelCase=False					)    ->    int:







   """simple docstring"""
   try:
      lowerCamelCase__       :						List[Any]        =							os.environ[key]
   except KeyError:
      # KEY isn't set, default to `default`.
      lowerCamelCase__       :						Optional[Any]        =							default
   else:
      # KEY is set, convert it to True or False.
      try:
         lowerCamelCase__       :						Tuple        =							strtobool(UpperCAmelCase					)
      except ValueError:
         # More values are supported, but let's keep the message simple.
         raise ValueError(f"If set, {key} must be yes or no."					)
   return _value


_A :   Tuple  			=  parse_flag_from_env('RUN_SLOW', default=False)
_A :   Optional[int]  			=  parse_flag_from_env('RUN_REMOTE', default=False)
_A :   List[str]  			=  parse_flag_from_env('RUN_LOCAL', default=True)
_A :   Any  			=  parse_flag_from_env('RUN_PACKAGED', default=True)

# Compression
_A :   Any  			=  pytest.mark.skipif(not config.LZ4_AVAILABLE, reason='test requires lz4')
_A :   str  			=  pytest.mark.skipif(not config.PY7ZR_AVAILABLE, reason='test requires py7zr')
_A :   Optional[int]  			=  pytest.mark.skipif(not config.ZSTANDARD_AVAILABLE, reason='test requires zstandard')

# Audio
_A :   int  			=  pytest.mark.skipif(
    # On Windows and OS X, soundfile installs sndfile
    find_spec('soundfile') is None or version.parse(importlib_metadata.version('soundfile')) < version.parse('0.12.0'),
    reason='test requires sndfile>=0.12.1: \'pip install \"soundfile>=0.12.1\"\'; ',
)

# Beam
_A :   Dict  			=  pytest.mark.skipif(
    not config.BEAM_AVAILABLE or config.DILL_VERSION >= version.parse('0.3.2'),
    reason='test requires apache-beam and a compatible dill version',
)

# Dill-cloudpickle compatibility
_A :   List[Any]  			=  pytest.mark.skipif(
    config.DILL_VERSION <= version.parse('0.3.2'),
    reason='test requires dill>0.3.2 for cloudpickle compatibility',
)

# Windows
_A :   List[str]  			=  pytest.mark.skipif(
    sys.platform == 'win32',
    reason='test should not be run on Windows',
)



def 	_a						(   UpperCAmelCase					)    ->    Union[str, Any]:







   """simple docstring"""
   try:
      import faiss  # noqa
   except ImportError:
      lowerCamelCase__       :						List[str]        =							unittest.skip('''test requires faiss'''					)(UpperCAmelCase					)
   return test_case



def 	_a						(   UpperCAmelCase					)    ->    List[str]:







   """simple docstring"""
   try:
      import regex  # noqa
   except ImportError:
      lowerCamelCase__       :						Optional[Any]        =							unittest.skip('''test requires regex'''					)(UpperCAmelCase					)
   return test_case



def 	_a						(   UpperCAmelCase					)    ->    List[Any]:







   """simple docstring"""
   try:
      import elasticsearch  # noqa
   except ImportError:
      lowerCamelCase__       :						Dict        =							unittest.skip('''test requires elasticsearch'''					)(UpperCAmelCase					)
   return test_case



def 	_a						(   UpperCAmelCase					)    ->    Optional[Any]:







   """simple docstring"""
   try:
      import sqlalchemy  # noqa
   except ImportError:
      lowerCamelCase__       :						str        =							unittest.skip('''test requires sqlalchemy'''					)(UpperCAmelCase					)
   return test_case



def 	_a						(   UpperCAmelCase					)    ->    Dict:







   """simple docstring"""
   if not config.TORCH_AVAILABLE:
      lowerCamelCase__       :						Dict        =							unittest.skip('''test requires PyTorch'''					)(UpperCAmelCase					)
   return test_case



def 	_a						(   UpperCAmelCase					)    ->    int:







   """simple docstring"""
   if not config.TF_AVAILABLE:
      lowerCamelCase__       :						int        =							unittest.skip('''test requires TensorFlow'''					)(UpperCAmelCase					)
   return test_case



def 	_a						(   UpperCAmelCase					)    ->    List[str]:







   """simple docstring"""
   if not config.JAX_AVAILABLE:
      lowerCamelCase__       :						Dict        =							unittest.skip('''test requires JAX'''					)(UpperCAmelCase					)
   return test_case



def 	_a						(   UpperCAmelCase					)    ->    str:







   """simple docstring"""
   if not config.PIL_AVAILABLE:
      lowerCamelCase__       :						Tuple        =							unittest.skip('''test requires Pillow'''					)(UpperCAmelCase					)
   return test_case



def 	_a						(   UpperCAmelCase					)    ->    Tuple:







   """simple docstring"""
   try:
      import transformers  # noqa F401
   except ImportError:
      return unittest.skip('''test requires transformers'''					)(UpperCAmelCase					)
   else:
      return test_case



def 	_a						(   UpperCAmelCase					)    ->    Any:







   """simple docstring"""
   try:
      import tiktoken  # noqa F401
   except ImportError:
      return unittest.skip('''test requires tiktoken'''					)(UpperCAmelCase					)
   else:
      return test_case



def 	_a						(   UpperCAmelCase					)    ->    List[Any]:







   """simple docstring"""
   try:
      import spacy  # noqa F401
   except ImportError:
      return unittest.skip('''test requires spacy'''					)(UpperCAmelCase					)
   else:
      return test_case



def 	_a						(   UpperCAmelCase					)    ->    Optional[int]:







   """simple docstring"""

   def _require_spacy_model(UpperCAmelCase					):
      try:
         import spacy  # noqa F401

         spacy.load(UpperCAmelCase					)
      except ImportError:
         return unittest.skip('''test requires spacy'''					)(UpperCAmelCase					)
      except OSError:
         return unittest.skip('''test requires spacy model \'{}\''''.format(UpperCAmelCase					)					)(UpperCAmelCase					)
      else:
         return test_case

   return _require_spacy_model



def 	_a						(   UpperCAmelCase					)    ->    int:







   """simple docstring"""
   try:
      import pyspark  # noqa F401
   except ImportError:
      return unittest.skip('''test requires pyspark'''					)(UpperCAmelCase					)
   else:
      return test_case



def 	_a						(   UpperCAmelCase					)    ->    List[str]:







   """simple docstring"""
   try:
      import joblibspark  # noqa F401
   except ImportError:
      return unittest.skip('''test requires joblibspark'''					)(UpperCAmelCase					)
   else:
      return test_case



def 	_a						(   UpperCAmelCase					)    ->    Optional[Any]:







   """simple docstring"""
   if not _run_slow_tests or _run_slow_tests == 0:
      lowerCamelCase__       :						List[Any]        =							unittest.skip('''test is slow'''					)(UpperCAmelCase					)
   return test_case



def 	_a						(   UpperCAmelCase					)    ->    Dict:







   """simple docstring"""
   if not _run_local_tests or _run_local_tests == 0:
      lowerCamelCase__       :						Tuple        =							unittest.skip('''test is local'''					)(UpperCAmelCase					)
   return test_case



def 	_a						(   UpperCAmelCase					)    ->    Union[str, Any]:







   """simple docstring"""
   if not _run_packaged_tests or _run_packaged_tests == 0:
      lowerCamelCase__       :						Union[str, Any]        =							unittest.skip('''test is packaged'''					)(UpperCAmelCase					)
   return test_case



def 	_a						(   UpperCAmelCase					)    ->    str:







   """simple docstring"""
   if not _run_remote_tests or _run_remote_tests == 0:
      lowerCamelCase__       :						Tuple        =							unittest.skip('''test requires remote'''					)(UpperCAmelCase					)
   return test_case



def 	_a						(   *UpperCAmelCase					)    ->    List[Any]:







   """simple docstring"""
   def decorate(cls					):
      for name, fn in cls.__dict__.items():
         if callable(UpperCAmelCase					) and name.startswith('''test'''					):
            for decorator in decorators:
               lowerCamelCase__       :						Any        =							decorator(UpperCAmelCase					)
            setattr(cls      ,  UpperCAmelCase      ,  UpperCAmelCase					)
      return cls

   return decorate


class        __SCREAMING_SNAKE_CASE      (			lowerCAmelCase_ ):
       pass


class        __SCREAMING_SNAKE_CASE      (			lowerCAmelCase_ ):
       _UpperCAmelCase				:  Any			   =   0
       _UpperCAmelCase				:  List[Any]			   =   1
       _UpperCAmelCase				:  Dict			   =   2



@contextmanager
def 	_a						(   UpperCAmelCase=OfflineSimulationMode.CONNECTION_FAILS      ,  UpperCAmelCase=1E-1_6					)    ->    Optional[int]:







   """simple docstring"""
   lowerCamelCase__       :						List[str]        =							requests.Session().request

   def timeout_request(UpperCAmelCase      ,  UpperCAmelCase      ,  UpperCAmelCase      ,  **UpperCAmelCase					):
      # Change the url to an invalid url so that the connection hangs
      lowerCamelCase__       :						List[str]        =							'''https://10.255.255.1'''
      if kwargs.get('''timeout'''					) is None:
         raise RequestWouldHangIndefinitelyError(
             f"Tried a call to {url} in offline mode with no timeout set. Please set a timeout."					)
      lowerCamelCase__       :						int        =							timeout
      try:
         return online_request(UpperCAmelCase      ,  UpperCAmelCase      ,  **UpperCAmelCase					)
      except Exception as e:
         # The following changes in the error are just here to make the offline timeout error prettier
         lowerCamelCase__       :						Union[str, Any]        =							url
         lowerCamelCase__       :						Tuple        =							e.args[0]
         lowerCamelCase__       :						str        =							(max_retry_error.args[0].replace('''10.255.255.1'''      ,  f"OfflineMock[{url}]"					),)
         lowerCamelCase__       :						str        =							(max_retry_error,)
         raise

   def raise_connection_error(UpperCAmelCase      ,  UpperCAmelCase      ,  **UpperCAmelCase					):
      raise requests.ConnectionError('''Offline mode is enabled.'''      ,  request=UpperCAmelCase					)

   if mode is OfflineSimulationMode.CONNECTION_FAILS:
      with patch('''requests.Session.send'''      ,  UpperCAmelCase					):
         yield
   elif mode is OfflineSimulationMode.CONNECTION_TIMES_OUT:
      # inspired from https://stackoverflow.com/a/904609
      with patch('''requests.Session.request'''      ,  UpperCAmelCase					):
         yield
   elif mode is OfflineSimulationMode.HF_DATASETS_OFFLINE_SET_TO_1:
      with patch('''datasets.config.HF_DATASETS_OFFLINE'''      ,  UpperCAmelCase					):
         yield
   else:
      raise ValueError('''Please use a value from the OfflineSimulationMode enum.'''					)



@contextmanager
def 	_a						(   *UpperCAmelCase      ,  **UpperCAmelCase					)    ->    Tuple:







   """simple docstring"""
   lowerCamelCase__       :						Optional[int]        =							str(Path().resolve()					)
   with tempfile.TemporaryDirectory(*UpperCAmelCase      ,  **UpperCAmelCase					) as tmp_dir:
      try:
         os.chdir(UpperCAmelCase					)
         yield
      finally:
         os.chdir(UpperCAmelCase					)



@contextmanager
def 	_a						(   )    ->    Optional[int]:







   """simple docstring"""
   import gc

   gc.collect()
   lowerCamelCase__       :						Optional[int]        =							pa.total_allocated_bytes()
   yield
   assert pa.total_allocated_bytes() - previous_allocated_memory > 0, "Arrow memory didn't increase."



@contextmanager
def 	_a						(   )    ->    Any:







   """simple docstring"""
   import gc

   gc.collect()
   lowerCamelCase__       :						str        =							pa.total_allocated_bytes()
   yield
   assert pa.total_allocated_bytes() - previous_allocated_memory <= 0, "Arrow memory wasn't expected to increase."



def 	_a						(   UpperCAmelCase      ,  UpperCAmelCase					)    ->    int:







   """simple docstring"""
   return deepcopy(UpperCAmelCase					).integers(0      ,  100      ,  10					).tolist() == deepcopy(UpperCAmelCase					).integers(0      ,  100      ,  10					).tolist()



def 	_a						(   UpperCAmelCase					)    ->    Any:







   """simple docstring"""
   import decorator
   from requests.exceptions import HTTPError

   def _wrapper(UpperCAmelCase      ,  *UpperCAmelCase      ,  **UpperCAmelCase					):
      try:
         return func(*UpperCAmelCase      ,  **UpperCAmelCase					)
      except HTTPError as err:
         if str(UpperCAmelCase					).startswith('''500'''					) or str(UpperCAmelCase					).startswith('''502'''					):
            pytest.xfail(str(UpperCAmelCase					)					)
         raise err

   return decorator.decorator(_wrapper      ,  UpperCAmelCase					)


class        __SCREAMING_SNAKE_CASE      :







       def __init__(				self					:     Any		, A					:     Optional[Any]		, A					:     List[str]		, A					:     List[str]      )       ->int:
          lowerCamelCase__       :						int        =							returncode
          lowerCamelCase__       :						int        =							stdout
          lowerCamelCase__       :						Union[str, Any]        =							stderr



async def 	_a						(   UpperCAmelCase      ,  UpperCAmelCase					)    ->    Dict:







   """simple docstring"""
   while True:
      lowerCamelCase__       :						List[str]        =							await stream.readline()
      if line:
         callback(UpperCAmelCase					)
      else:
         break



async def 	_a						(   UpperCAmelCase      ,  UpperCAmelCase=None      ,  UpperCAmelCase=None      ,  UpperCAmelCase=None      ,  UpperCAmelCase=False      ,  UpperCAmelCase=False					)    ->    _RunOutput:







   """simple docstring"""
   if echo:
      print('''\nRunning: '''      ,  ''' '''.join(UpperCAmelCase					)					)

   lowerCamelCase__       :						Optional[Any]        =							await asyncio.create_subprocess_exec(
       cmd[0]      ,  *cmd[1:]      ,  stdin=UpperCAmelCase      ,  stdout=asyncio.subprocess.PIPE      ,  stderr=asyncio.subprocess.PIPE      ,  env=UpperCAmelCase      ,  )

   # note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe
   # https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait
   #
   # If it starts hanging, will need to switch to the following code. The problem is that no data
   # will be seen until it's done and if it hangs for example there will be no debug info.
   # out, err = await p.communicate()
   # return _RunOutput(p.returncode, out, err)

   lowerCamelCase__       :						List[Any]        =							[]
   lowerCamelCase__       :						Optional[Any]        =							[]

   def tee(UpperCAmelCase      ,  UpperCAmelCase      ,  UpperCAmelCase      ,  UpperCAmelCase=""					):
      lowerCamelCase__       :						Any        =							line.decode('''utf-8'''					).rstrip()
      sink.append(UpperCAmelCase					)
      if not quiet:
         print(UpperCAmelCase      ,  UpperCAmelCase      ,  file=UpperCAmelCase					)

    # XXX: the timeout doesn't seem to make any difference here
   await asyncio.wait(
       [
           _read_stream(p.stdout      ,  lambda UpperCAmelCase					: tee(UpperCAmelCase      ,  UpperCAmelCase      ,  sys.stdout      ,  label='''stdout:'''					)					),
           _read_stream(p.stderr      ,  lambda UpperCAmelCase					: tee(UpperCAmelCase      ,  UpperCAmelCase      ,  sys.stderr      ,  label='''stderr:'''					)					),
       ]      ,  timeout=UpperCAmelCase      ,  )
   return _RunOutput(await p.wait()      ,  UpperCAmelCase      ,  UpperCAmelCase					)



def 	_a						(   UpperCAmelCase      ,  UpperCAmelCase=None      ,  UpperCAmelCase=None      ,  UpperCAmelCase=180      ,  UpperCAmelCase=False      ,  UpperCAmelCase=True					)    ->    _RunOutput:







   """simple docstring"""
   lowerCamelCase__       :						Dict        =							asyncio.get_event_loop()
   lowerCamelCase__       :						Union[str, Any]        =							loop.run_until_complete(
       _stream_subprocess(UpperCAmelCase      ,  env=UpperCAmelCase      ,  stdin=UpperCAmelCase      ,  timeout=UpperCAmelCase      ,  quiet=UpperCAmelCase      ,  echo=UpperCAmelCase					)					)

   lowerCamelCase__       :						Any        =							''' '''.join(UpperCAmelCase					)
   if result.returncode > 0:
      lowerCamelCase__       :						Optional[Any]        =							'''\n'''.join(result.stderr					)
      raise RuntimeError(
          f"'{cmd_str}' failed with returncode {result.returncode}\n\n"
          f"The combined stderr from workers follows:\n{stderr}"					)

   # check that the subprocess actually did run and produced some output, should the test rely on
   # the remote side to do the testing
   if not result.stdout and not result.stderr:
      raise RuntimeError(f"'{cmd_str}' produced no output."					)

   return result



def 	_a						(   )    ->    Optional[Any]:







   """simple docstring"""
   lowerCamelCase__       :						Dict        =							os.environ.get('''PYTEST_XDIST_WORKER'''      ,  '''gw0'''					)
   lowerCamelCase__       :						Union[str, Any]        =							re.sub(R'''^gw'''      ,  ''''''      ,  UpperCAmelCase      ,  0      ,  re.M					)
   return int(UpperCAmelCase					)




def 	_a						(   )    ->    str:







   """simple docstring"""
   lowerCamelCase__       :						str        =							29500
   lowerCamelCase__       :						Optional[Any]        =							pytest_xdist_worker_id()
   return port + uniq_delta










from __future__ import annotations

_A :   List[str]  			=  '#'


class        __SCREAMING_SNAKE_CASE      :







       def __init__(				self					:     List[Any]      )       ->None:
          lowerCamelCase__       :						dict        =							{}







       def 						__lowerCamelCase   (				self					:     Union[str, Any]		, A					:     str      )       ->None:
          lowerCamelCase__       :						Any        =							self._trie
          for char in text:
             if char not in trie:
                lowerCamelCase__       :						Any        =							{}
             lowerCamelCase__       :						Any        =							trie[char]
          lowerCamelCase__       :						List[str]        =							True







       def 						__lowerCamelCase   (				self					:     List[Any]		, A					:     str      )       ->tuple | list:
          lowerCamelCase__       :						Dict        =							self._trie
          for char in prefix:
             if char in trie:
                lowerCamelCase__       :						List[Any]        =							trie[char]
             else:
                return []
          return self._elements(A      )







       def 						__lowerCamelCase   (				self					:     Dict		, A					:     dict      )       ->tuple:
          lowerCamelCase__       :						Optional[Any]        =							[]
          for c, v in d.items():
             lowerCamelCase__       :						Any        =							[''' '''] if c == END else [(c + s) for s in self._elements(A      )]
             result.extend(A      )
          return tuple(A      )


_A :   str  			=  Trie()
_A :   List[Any]  			=  ('depart', 'detergent', 'daring', 'dog', 'deer', 'deal')
for word in words:
       trie.insert_word(word)



def 	_a						(   UpperCAmelCase					)    ->    tuple:







   """simple docstring"""
   lowerCamelCase__       :						Optional[int]        =							trie.find_word(UpperCAmelCase					)
   return tuple(string + word for word in suffixes					)



def 	_a						(   )    ->    None:







   """simple docstring"""
   print(autocomplete_using_trie('''de'''					)					)


if __name__ == "__main__":
       import doctest

       doctest.testmod()
       main()



