





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     __UpperCamelCase						(_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE=False	)       ->     int:
  try:
    lowercase__			    =						os.environ[key]
  except KeyError:
    # KEY isn't set, default to `default`.
    lowercase__			    =						default
  else:
    # KEY is set, convert it to True or False.
    try:
      lowercase__			    =						strtobool(_SCREAMING_SNAKE_CASE	)
    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


lowercase_					     =	parse_flag_from_env("""RUN_SLOW""", default=False)
lowercase_					     =	parse_flag_from_env("""RUN_REMOTE""", default=False)
lowercase_					     =	parse_flag_from_env("""RUN_LOCAL""", default=True)
lowercase_					     =	parse_flag_from_env("""RUN_PACKAGED""", default=True)

# Compression
lowercase_					     =	pytest.mark.skipif(not config.LZ4_AVAILABLE, reason="""test requires lz4""")
lowercase_					     =	pytest.mark.skipif(not config.PY7ZR_AVAILABLE, reason="""test requires py7zr""")
lowercase_					     =	pytest.mark.skipif(not config.ZSTANDARD_AVAILABLE, reason="""test requires zstandard""")

# Audio
lowercase_					     =	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
lowercase_					     =	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
lowercase_					     =	pytest.mark.skipif(
    config.DILL_VERSION <= version.parse("""0.3.2"""),
    reason="""test requires dill>0.3.2 for cloudpickle compatibility""",
)

# Windows
lowercase_					     =	pytest.mark.skipif(
    sys.platform == """win32""",
    reason="""test should not be run on Windows""",
)




def     __UpperCamelCase						(_SCREAMING_SNAKE_CASE	)       ->     List[Any]:
  try:
    import faiss  # noqa
  except ImportError:
    lowercase__			    =						unittest.skip('test requires faiss'	)(_SCREAMING_SNAKE_CASE	)
  return test_case




def     __UpperCamelCase						(_SCREAMING_SNAKE_CASE	)       ->     List[str]:
  try:
    import regex  # noqa
  except ImportError:
    lowercase__			    =						unittest.skip('test requires regex'	)(_SCREAMING_SNAKE_CASE	)
  return test_case




def     __UpperCamelCase						(_SCREAMING_SNAKE_CASE	)       ->     str:
  try:
    import elasticsearch  # noqa
  except ImportError:
    lowercase__			    =						unittest.skip('test requires elasticsearch'	)(_SCREAMING_SNAKE_CASE	)
  return test_case




def     __UpperCamelCase						(_SCREAMING_SNAKE_CASE	)       ->     Dict:
  try:
    import sqlalchemy  # noqa
  except ImportError:
    lowercase__			    =						unittest.skip('test requires sqlalchemy'	)(_SCREAMING_SNAKE_CASE	)
  return test_case




def     __UpperCamelCase						(_SCREAMING_SNAKE_CASE	)       ->     Optional[int]:
  if not config.TORCH_AVAILABLE:
    lowercase__			    =						unittest.skip('test requires PyTorch'	)(_SCREAMING_SNAKE_CASE	)
  return test_case




def     __UpperCamelCase						(_SCREAMING_SNAKE_CASE	)       ->     Dict:
  if not config.TF_AVAILABLE:
    lowercase__			    =						unittest.skip('test requires TensorFlow'	)(_SCREAMING_SNAKE_CASE	)
  return test_case




def     __UpperCamelCase						(_SCREAMING_SNAKE_CASE	)       ->     Optional[int]:
  if not config.JAX_AVAILABLE:
    lowercase__			    =						unittest.skip('test requires JAX'	)(_SCREAMING_SNAKE_CASE	)
  return test_case




def     __UpperCamelCase						(_SCREAMING_SNAKE_CASE	)       ->     str:
  if not config.PIL_AVAILABLE:
    lowercase__			    =						unittest.skip('test requires Pillow'	)(_SCREAMING_SNAKE_CASE	)
  return test_case




def     __UpperCamelCase						(_SCREAMING_SNAKE_CASE	)       ->     int:
  try:
    import transformers  # noqa F401
  except ImportError:
    return unittest.skip('test requires transformers'	)(_SCREAMING_SNAKE_CASE	)
  else:
    return test_case




def     __UpperCamelCase						(_SCREAMING_SNAKE_CASE	)       ->     List[str]:
  try:
    import tiktoken  # noqa F401
  except ImportError:
    return unittest.skip('test requires tiktoken'	)(_SCREAMING_SNAKE_CASE	)
  else:
    return test_case




def     __UpperCamelCase						(_SCREAMING_SNAKE_CASE	)       ->     Any:
  try:
    import spacy  # noqa F401
  except ImportError:
    return unittest.skip('test requires spacy'	)(_SCREAMING_SNAKE_CASE	)
  else:
    return test_case




def     __UpperCamelCase						(_SCREAMING_SNAKE_CASE	)       ->     Dict:

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

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

  return _require_spacy_model




def     __UpperCamelCase						(_SCREAMING_SNAKE_CASE	)       ->     List[Any]:
  try:
    import pyspark  # noqa F401
  except ImportError:
    return unittest.skip('test requires pyspark'	)(_SCREAMING_SNAKE_CASE	)
  else:
    return test_case




def     __UpperCamelCase						(_SCREAMING_SNAKE_CASE	)       ->     int:
  try:
    import joblibspark  # noqa F401
  except ImportError:
    return unittest.skip('test requires joblibspark'	)(_SCREAMING_SNAKE_CASE	)
  else:
    return test_case




def     __UpperCamelCase						(_SCREAMING_SNAKE_CASE	)       ->     Optional[Any]:
  if not _run_slow_tests or _run_slow_tests == 0:
    lowercase__			    =						unittest.skip('test is slow'	)(_SCREAMING_SNAKE_CASE	)
  return test_case




def     __UpperCamelCase						(_SCREAMING_SNAKE_CASE	)       ->     Tuple:
  if not _run_local_tests or _run_local_tests == 0:
    lowercase__			    =						unittest.skip('test is local'	)(_SCREAMING_SNAKE_CASE	)
  return test_case




def     __UpperCamelCase						(_SCREAMING_SNAKE_CASE	)       ->     List[str]:
  if not _run_packaged_tests or _run_packaged_tests == 0:
    lowercase__			    =						unittest.skip('test is packaged'	)(_SCREAMING_SNAKE_CASE	)
  return test_case




def     __UpperCamelCase						(_SCREAMING_SNAKE_CASE	)       ->     Optional[int]:
  if not _run_remote_tests or _run_remote_tests == 0:
    lowercase__			    =						unittest.skip('test requires remote'	)(_SCREAMING_SNAKE_CASE	)
  return test_case




def     __UpperCamelCase						(*_SCREAMING_SNAKE_CASE	)       ->     Tuple:
  def decorate(cls	):
    for name, fn in cls.__dict__.items():
      if callable(_SCREAMING_SNAKE_CASE	) and name.startswith('test'	):
        for decorator in decorators:
          lowercase__			    =						decorator(_SCREAMING_SNAKE_CASE	)
        setattr(cls	,		_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	)
    return cls

  return decorate
class        SCREAMING_SNAKE_CASE     (UpperCAmelCase   ):
   pass






class        SCREAMING_SNAKE_CASE     (UpperCAmelCase   ):
   _UpperCamelCase					:	List[Any]				      = 0
   _UpperCamelCase					:	Any				      = 1
   _UpperCamelCase					:	Optional[Any]				      = 2






@contextmanager
def     __UpperCamelCase						(_SCREAMING_SNAKE_CASE=OfflineSimulationMode.CONNECTION_FAILS	,		_SCREAMING_SNAKE_CASE=1E-16	)       ->     Tuple:
  lowercase__			    =						requests.Session().request

  def timeout_request(_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	,		**_SCREAMING_SNAKE_CASE	):
    # Change the url to an invalid url so that the connection hangs
    lowercase__			    =						'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."""	)
    lowercase__			    =						timeout
    try:
      return online_request(_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	,		**_SCREAMING_SNAKE_CASE	)
    except Exception as e:
      # The following changes in the error are just here to make the offline timeout error prettier
      lowercase__			    =						url
      lowercase__			    =						e.args[0]
      lowercase__			    =						(max_retry_error.args[0].replace('10.255.255.1'	,		F"""OfflineMock[{url}]"""	),)
      lowercase__			    =						(max_retry_error,)
      raise

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

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




@contextmanager
def     __UpperCamelCase						(*_SCREAMING_SNAKE_CASE	,		**_SCREAMING_SNAKE_CASE	)       ->     Dict:
  lowercase__			    =						str(Path().resolve()	)
  with tempfile.TemporaryDirectory(*_SCREAMING_SNAKE_CASE	,		**_SCREAMING_SNAKE_CASE	) as tmp_dir:
    try:
      os.chdir(_SCREAMING_SNAKE_CASE	)
      yield
    finally:
      os.chdir(_SCREAMING_SNAKE_CASE	)




@contextmanager
def     __UpperCamelCase						()       ->     str:
  import gc

  gc.collect()
  lowercase__			    =						pa.total_allocated_bytes()
  yield
  assert pa.total_allocated_bytes() - previous_allocated_memory > 0, "Arrow memory didn't increase."




@contextmanager
def     __UpperCamelCase						()       ->     Tuple:
  import gc

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




def     __UpperCamelCase						(_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	)       ->     Dict:
  return deepcopy(_SCREAMING_SNAKE_CASE	).integers(0	,		100	,		10	).tolist() == deepcopy(_SCREAMING_SNAKE_CASE	).integers(0	,		100	,		10	).tolist()




def     __UpperCamelCase						(_SCREAMING_SNAKE_CASE	)       ->     List[str]:
  import decorator
  from requests.exceptions import HTTPError

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

  return decorator.decorator(_wrapper	,		_SCREAMING_SNAKE_CASE	)
class        SCREAMING_SNAKE_CASE     :


   def __init__(					self    :       List[str]    ,  a    :       List[Any]    ,  a    :       Any    ,  a    :       Optional[int] )->     List[str]:





     """simple docstring"""







     lowercase__			    =						returncode
     lowercase__			    =						stdout
     lowercase__			    =						stderr






async def     __UpperCamelCase						(_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	)       ->     List[Any]:
  while True:
    lowercase__			    =						await stream.readline()
    if line:
      callback(_SCREAMING_SNAKE_CASE	)
    else:
      break




async def     __UpperCamelCase						(_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE=None	,		_SCREAMING_SNAKE_CASE=None	,		_SCREAMING_SNAKE_CASE=None	,		_SCREAMING_SNAKE_CASE=False	,		_SCREAMING_SNAKE_CASE=False	)       ->     _RunOutput:
  if echo:
    print('\nRunning: '	,		' '.join(_SCREAMING_SNAKE_CASE	)	)

  lowercase__			    =						await asyncio.create_subprocess_exec(
      cmd[0]	,		*cmd[1:]	,		stdin=_SCREAMING_SNAKE_CASE	,		stdout=asyncio.subprocess.PIPE	,		stderr=asyncio.subprocess.PIPE	,		env=_SCREAMING_SNAKE_CASE	,		)

  # 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)

  lowercase__			    =						[]
  lowercase__			    =						[]

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

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




def     __UpperCamelCase						(_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE=None	,		_SCREAMING_SNAKE_CASE=None	,		_SCREAMING_SNAKE_CASE=180	,		_SCREAMING_SNAKE_CASE=False	,		_SCREAMING_SNAKE_CASE=True	)       ->     _RunOutput:
  lowercase__			    =						asyncio.get_event_loop()
  lowercase__			    =						loop.run_until_complete(
      _stream_subprocess(_SCREAMING_SNAKE_CASE	,		env=_SCREAMING_SNAKE_CASE	,		stdin=_SCREAMING_SNAKE_CASE	,		timeout=_SCREAMING_SNAKE_CASE	,		quiet=_SCREAMING_SNAKE_CASE	,		echo=_SCREAMING_SNAKE_CASE	)	)

  lowercase__			    =						' '.join(_SCREAMING_SNAKE_CASE	)
  if result.returncode > 0:
    lowercase__			    =						'\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     __UpperCamelCase						()       ->     List[str]:
  lowercase__			    =						os.environ.get('PYTEST_XDIST_WORKER'	,		'gw0'	)
  lowercase__			    =						re.sub(R'^gw'	,		''	,		_SCREAMING_SNAKE_CASE	,		0	,		re.M	)
  return int(_SCREAMING_SNAKE_CASE	)




def     __UpperCamelCase						()       ->     Optional[int]:
  lowercase__			    =						29500
  lowercase__			    =						pytest_xdist_worker_id()
  return port + uniq_delta








class        SCREAMING_SNAKE_CASE     :  # Public class to implement a graph


   def __init__(					self    :       int    ,  a    :       int    ,  a    :       int    ,  a    :       list[list[bool]] )->     None:





     """simple docstring"""







     lowercase__			    =						row
     lowercase__			    =						col
     lowercase__			    =						graph


   def  SCREAMING_SNAKE_CASE_							(					self    :       Dict    ,  a    :       int    ,  a    :       int    ,  a    :       list[list[bool]] )->     bool:





     """simple docstring"""







     return (
         0 <= i < self.ROW
         and 0 <= j < self.COL
         and not visited[i][j]
         and self.graph[i][j]
     )


   def  SCREAMING_SNAKE_CASE_							(					self    :       List[str]    ,  a    :       int    ,  a    :       int    ,  a    :       list[list[bool]] )->     None:





     """simple docstring"""







     lowercase__			    =						[-1, -1, -1, 0, 0, 1, 1, 1]  # Coordinate order
     lowercase__			    =						[-1, 0, 1, -1, 1, -1, 0, 1]
     lowercase__			    =						True  # Make those cells visited
     for k in range(8 ):
       if self.is_safe(i + row_nbr[k]    ,  j + col_nbr[k]    ,  a ):
         self.diffs(i + row_nbr[k]    ,  j + col_nbr[k]    ,  a )


   def  SCREAMING_SNAKE_CASE_							(					self    :       List[str] )->     int:  # And finally, count all islands.





     """simple docstring"""







     lowercase__			    =						[[False for j in range(self.COL )] for i in range(self.ROW )]
     lowercase__			    =						0
     for i in range(self.ROW ):
       for j in range(self.COL ):
         if visited[i][j] is False and self.graph[i][j] == 1:
           self.diffs(a    ,  a    ,  a )
           count += 1
     return count


